Laravel - Use of Accessors and Mutators to format Eloquent attributes

Laravel - Use of Accessors and Mutators to format Eloquent attributes

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 one

In this example, i have a "User" model with following fields :

  • first_name
  • last_name
  • email
  • 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:

  1. function getFullNameAttribute()
  2. {
  3. return $this->attributes['first_name'] . ' ' . $this->attributes['last_name'];
  4. }

Now you can get the full_name in following way :

  1. $user = App\User::find(1); // works!
  2. echo $user->full_name;
Order Results by Accessors Attribute?

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.

  1. $users = User::orderBy('full_name')->get(); // doesn't work

Solution is very simple to get user list in order using sortBy and sortByDesc method.

  1. $users = User::get()->sortBy('full_name'); // works!
  2. return $users;
Defining a Mutators

Mutators use setAttribute to format field before saving into database.

Capitalize the first name before saving

In this example, We will capitalize the first name with the help of mutators in following way:

  1. public function setFirstNameAttribute($value)
  2. {
  3. $this->attributes['first_name'] = ucfirst($value);
  4. }
Hashing Passwords

Never save your password as plain text into your database. Here is quick example to bcrypt the password before save.

  1. public function setPasswordAttribute($value) {
  2. $this->attributes['password'] = bcrypt($value);
  3. }

Phone: (+91) 8800417876
Noida, 201301
sakarya escort akyazı escort arifiye escort erenler escort eve gelen escort ferizli escort geyve escort hendek escort otele gelen escort sapanca escort söğütlü escort taraklı escort
sakarya escort - akyazı escort - arifiye escort - erenler escort - eve gelen escort - ferizli escort - geyve escort - hendek escort - karapürçek escort - karasu escort - kaynarca escort - kocaali escort - otele gelen escort - pamukova escort - sapanca escort - söğütlü escort - taraklı escort
sapanca escort hendek escort karasu escort escort sakarya sakarya escort bayan adapazarı escort sakarya escort sakarya escort sakarya escort sakarya escort sakarya escort sakarya escort