Laravel Accessors & Mutators

Created on November 5th, 2015

This could be the most common overlooked feature in Laravel, yet it's a super easy concept. So, in this video we'll show you how to use accessors and mutators in your Laravel application. The concept is actually very simple. An accessor allows you to manipulate the data as it is accessed from the database, and a mutator allows you to manipulate the data inserted into a table before it actually gets inserted into the database.

Below you will find the simple accessors we created in the video (accessors allow us to manipulate data as we access it from the database):

public function getNameAttribute($value){
    return ucwords($value);
}

public function getEmailAttribute($value){
    return strtolower($value);
}

Next are the mutators that we created (Mutators allow us to manipulate data before it gets inserted into the database):

public function setNameAttribute($value){
    $this->attributes['name'] = ucwords($value);
}

public function setEmailAttribute($value){
    $this->attributes['email'] = strtolower($value);
}

And that's all there is to accessors and mutators :)

Comments (0)