Laravel - Mutators / Casts - Defining A Mutator

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

Let's define a mutator for the first_name attribute. This mutator will be automatically called when we attempt to set the value of the first_name attribute on the model:

    
    attributes['first_name'] = strtolower($value);
        }
    }
	

The mutator will receive the value that is being set on the attribute, allowing you to manipulate the value and set the manipulated value on the Eloquent model's internal $attributes property. To use our mutator, we only need to set the first_name attribute on an Eloquent model:

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

In this example, the setFirstNameAttribute function will be called with the value Sally. The mutator will then apply the strtolower function to the name and set its resulting value in the internal $attributes array.