Laravel - Mutators / Casts - Defining An Accessor

An accessor transforms an Eloquent attribute value when it is accessed. To define an accessor, create a get{Attribute}Attribute method on your model where {Attribute} is the "studly" cased name of the column you wish to access.

In this example, we'll define an accessor for the first_name attribute. The accessor will automatically be called by Eloquent when attempting to retrieve the value of the first_name attribute:


As you can see, the original value of the column is passed to the accessor, allowing you to manipulate and return the value. To access the value of the accessor, you may simply access the first_name attribute on a model instance:

    use App\Models\User;
    $user = User::find(1);
    $firstName = $user->first_name;

You are not limited to interacting with a single attribute within your accessor. You may also use accessors to return new, computed values from existing attributes:

     * Get the user's full name.
     * @return string
    public function getFullNameAttribute()
        return "{$this->first_name} {$this->last_name}";
If you would like these computed values to be added to the array / JSON representations of your model, you will need to append them.