Add custom columns to models

Submitted by osclancer - 8 months ago

Using laravel eloquent, you have an amazing feature called `Accessors`, which allows you to define a non-existing column, here's an example to get user full_name that does not exist in the users table

// User model

class User extends Authenticatable
{
    /**
     * Return the full_name by concatinating 
     * the first_name . ' ' . last_name
     *
     * @return String
     */
    function getFullNameAttribute() {
    
        return sprintf('%s %s', $this->first_name, $this->last_name);
    }
}

// Usage

User::first()->full_name;