What is $this attribute and how to use it in Laravel

In Laravel controllers code samples, you might have noticed of $this attribute when accessing database values. This works to define a mutator, for example, a setFooAttribute method in your model where Foo
is the “studly” cased name of the column you want to access.

Mutators and Accessors allow you to format Eloquent attributes when you retrieve them from a model or set up their value. For example, you may want to use the Laravel encrypter to encrypt a value while it is stored in your database, and then you automatically decrypt the attribute when you access it on an Eloquent model.

So, lets consider this example to define a mutator as the first_name attribute and refer to it with the $this attribute. This mutator will be automatically called when we attempt to set the value of the first_name
attribute on the model as shown below.

class User extends Model
{
    public function setFirstNameAttribute($value)
    {
        $this->attributes['first_name'] = strtolower($value);
    }
}

This way we can pass any function in the controller to apply to any database column as shown above. In this case, it takes in a $value, applied the strtolower function on it to move to lower case and then passes it to the database column ‘first_name’.

This mutator ‘setFirstNameAttribute‘ will be called automatically when we try to set the value of the first_name attribute on the model.

The mutator will then receive the value ($value) that is being set on the attribute (first_name). This allows you to manipulate the value in any way. In this case change it to lower case. You may then set the manipulated value on the Eloquent model’s internal $attributes property.

Leave a Comment