Sample Code for Creating Laravel Mutators

Mutators transform an Eloquent attribute value when it is set by the model. We can use mutators to manipulate, format, and transform the value being sent to the database by the model. In this article, we will show you a simple of how to use mutators with Laravel by hashing the password without writing any logic in the controller instead we automatically hash the password from the model.

Defining mutators to transform a field from its value

In the user model

<?php

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\Hash;

class User extends Authenticatable
{
    protected $fillable = [
        'firstname',
        'lastname',
        'email',
        'password',
    ];

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

Using a mutators

Here in the controller, we don’t need to hash the password as it will be auto-hash in the model. See the image below.

In the user controller

<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function create(Request $request)
    {
        $user = User::create($request->only('firstname', 'lastname', 'email', 'password'));
        return $user;
    }
}

In api.php

<?php

use App\Http\Controllers\UserController;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::post('user', [ UserController::class, 'create' ]);