Laravel Accessors and Mutators
I was working on a project that is in Laravel 8. And I needed to limit the words in the blade template. I tried using substr() and Str::substr() but nothing worked for me.
Then i started searching google and found Laravel Accessors and Mutators. You might have heard about it, no problem you never heard of them. we will discuss it here
What are Laravel Accessors?
Accessors are custom property that we define in the model to customize the output of the table column. We define it in Model when we have a case like,
let say we have columns in table first_name and last_name, and we want to show full name in our blades, native way of doing this is concatenation like
{{ $model->first_name . ‘ ‘ . $model->last_name }}
and the laravel way, in your model
class User extends Model {
public function getFullNameAttribute()
{
return $this->first_name. ‘ ‘ .$this->last_name;
}
}
Now you can access it like
$user->full_name
I am sure you might be confused here, that we never declare any function like full_name.
let me tell you this, there is s specific method of defining an accessor get[full_name]Attribute that becomes getFullNameAttribute. Hope you got it. But you can’t use this in your queries.
What are Laravel Mutators?
Laravel mutators are methods that we use to customize the value of the column before saving to the Database. Here is the difference between Accessors & Mutators, We use Accessors to customize the output of the table column and we use Mutators to customize the value of the column before saving to the table.
Let’s say you have a form with a text editor and you want to escape all HTML before saving to DB so here is the Laravel Mutator for this
Define a method in your Model, let say your column name is short_description
class User extends Model {
public function setShortDescriptionAttribute($value)
{
$this->attribute[‘short_description’] = stript_tags($value);
}
}
and in you can save your data like this
$user->short_description = $request->short_description;
That’s it.
In Laravel, every model object has two values original and attributes and by changing any value in the collection, we actually change the attribute value and that is what is getting stored in the database with the help of Laravel Accessors and Mutators or shown in the blade or anywhere you want to use.


Leave a Reply