In this tutorial, I will let you know the use of Accessors and Mutators
to automatically format database fields.
In short term, Accessors are used to format database fields when retrieving from the database and in the same way Mutators are used to format the attributes before saving to the database.
In the secure application, Mutators are commonly used to bcrypt the password before saving into the database.
Defining an Accessors Combine two attributes to create just oneIn this example, i have a "User" model with following fields :
- first_name
- last_name
- password
- created_at
- updated_at
Now we will combine first_name and last_name to get full_name with the help of accessors. We will create accessor method within the model in following way:
- function getFullNameAttribute()
- {
- return $this->attributes['first_name'] . ' ' . $this->attributes['last_name'];
- }
Now you can get the full_name in following way :
- $user = App\User::find(1); // works!
- echo $user->full_name;
If you want to order results by full_name using orderBy then it will throws an error because the full_name is not real attribute that exist in the database.
- $users = User::orderBy('full_name')->get(); // doesn't work
Solution is very simple to get user list in order using sortBy
and sortByDesc
method.
- $users = User::get()->sortBy('full_name'); // works!
- return $users;
Mutators use setAttribute
to format field before saving into database.
In this example, We will capitalize the first name with the help of mutators in following way:
- public function setFirstNameAttribute($value)
- {
- $this->attributes['first_name'] = ucfirst($value);
- }
Never save your password as plain text into your database. Here is quick example to bcrypt the password before save.
- public function setPasswordAttribute($value) {
- $this->attributes['password'] = bcrypt($value);
- }