Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

laravel
php
communitycreator

What are eloquent mutators in Laravel?

Zubair Idris Aweda

Eloquent mutators are used to determine how data is processed when it is stored. Eloquent mutators come into play when creating or updating a new database resource. For example, if you’d like to hash passwords before storing them, a mutator will be created for the password field, and whenever a password value is about to be inserted into the database, it gets hashed.

To define a mutator, create a public function in the model. Name the mutator using the rules below:

  • The name must start with set.
  • set should be followed by the attribute name in the Pascal case. For example, to mutate the full_name attribute, use FullName.
  • Finally, the name should end with Attribute.

Create a password mutator

To create a mutator for the password attribute, create a public function named setPasswordAttribute in the User model. This method takes in the current value of the field. This value may then be processed as you wish, and the field is updated.

To complete the password mutator, update the password to its hashed version.

public function setPasswordAttribute($password)
{
    $this->attributes['password'] = Hash::make($password);
}

The User model should be as follows:

<?php

namespace App\Models;

// Other imports
use Illuminate\Support\Facades\Hash;

class User extends Authenticatable
{
    use HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var string[]
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function setPasswordAttribute($password)
    {
        $this->attributes['password'] = Hash::make($password);
    }
}

Now, this sets the model’s password to the hashed version of whatever is passed in. This means you can create new database resources directly from user input and still get the password as hashed. For example:

Route::get('/register', function (Request $request) {
    User::create($request->only(['name', 'email', 'password']));
});

This example assumes the database has a name, email, and password field.

RELATED TAGS

laravel
php
communitycreator
RELATED COURSES

View all Courses

Keep Exploring