Laravel 9 Accessors and Mutators Eloquent Example

Sovary July 27, 2022 607
5 minutes read

We will learn how to use mutator and accessor in Laravel 9. Within examples accessor you will understand what is accessor in Laravel 9 and mutator. The following example below will help you when to use eloquent mutator and accessor in Laravel.

In Laravel 9 is quite different a little from early Laravel version. Mutator and Accessor in other word is like brothers, with more understand I will give simple definition what is Accessors and Mutators in Laravel Eloquent.

What is Accessor?

Accessor is user custom attribute on model class which we can access as attribute or database column, basically use to retrieve from database. In C# we may call this as Getter.

What is Mutator?

Mutator is user custom attribute on model class which we can set the format or custom data before insert into the database. In C# we may call this as Setter.

I will explain with simple example, in User Model class have new field call "biowe will give input format string in random letter case sometimes and when we want to retrieved the field back with lower case letter you may do this logic again and again in many places (Imagine If You Have Complicated logic and need Write Again and Again, This Is Not a Best Practice).

So, let's see below example and you will got it how it works.

Laravel Accessors and Mutators Eloquent

The following steps help you to understand how to use accessors and mutators in Laravel 9 :

  • Step 1 - Install Laravel 9 Project
  • Step 2 - Update Migration and Model
  • Step 3 - Create Accessor and Mutator in Model
  • Step 4 - Create Controller
  • Step 5 - Add Routes
  • Step 6 - Run Laravel App

Step 1 - Install Laravel 9 Project

You have to installed Laravel framework but not required if you already done. Read this to know how to install Laravel project.

Step 2 - Update Migration and Model

We are going to update a field name bio for user table, so let's update as code below:

Open file database -> migrations -> 2022_07_22_564781_create_users_table.php

<?php
  
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
  
return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->string('bio');
            $table->timestamps();
        });
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
};

After that run command below to migrate table into database.

php artisan migrate

Step 3 - Create Accessor and Mutator in Model

Basically, accessor and muatator are created in model class by extend from Attirube Class.

Open file app -> Models -> User.php

<?php
  
namespace App\Models;
  
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Carbon\Carbon;
  
class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
    /**
     * The attributes that are mass assignable.
     *
     * @var array

     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'bio'
    ];
  
    /**
     * 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',
    ];
  
    /**
     * Interact with the user's first name.
     *
     * @param  string  $value
     * @return \Illuminate\Database\Eloquent\Casts\Attribute
     */
    protected function bio(): Attribute
    {
        return new Attribute(
            get: fn ($value) =>  strtoupper($value),
            set: fn ($value) =>  strtolower($value),
        );
    }
}

Step 4 - Create Controller

Now, we are going to create a new UserController and we will create two new methods store() and show() by following command to generate controller file:

php artisan make:controller UserController

Open file app -> Http -> Controllers -> UserController.php

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\User;
  
class UserController extends Controller
{

    public function store()
    {
        $user = [
            'name' => 'cambo tutorial',
            'email' => 'cambo@tutorial.com',
            'password' => bcrypt('123456'),
            'bio' => 'This Document Should Be Unique And Personal. In The Same Vein'
        ];
  
        $data= User::create($user);
   
        dd($data);
    }
  
    public function show()
    {
        $user = User::all();
        dd($user->toArray());
    }
}

Step 5 - Add Routes

This step, you have mapping route controller and URL by following routes in the routes/web.php file.

Open file routes -> web.php

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\UserController;
  
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
  

Route::get('\store', [UserController::class,'create']);
Route::get('\show', [UserController::class,'show']);

Step 6 - Run Laravel App

Now we are going to start Laravel server by following command and see the result.

php artisan serve

Output Mutator go to link http://localhost:8000/store

It will create user and check the bio column the text is lowercase.

 

Output Accessor go to link http://localhost:8000/show

The data return from column bio is convert to uppercase

array:7 [
  "id" => 1
  "name" => "Cambo Tutorial"
  "email" => "cambo@tutorial.com"
  "email_verified_at" => null
  "created_at" => "2022-06-27T04:37:46.000000Z"
  "updated_at" => "2022-06-27T04:37:46.000000Z"
  "bio" => "THIS DOCUMENT SHOULD BE UNIQUE AND PERSONAL. IN THE SAME VEIN"

]

I hope this article helped you to learn about Eloquent Mutators and Accessors in Laravel 9. Please have a nice day!

You might also like...

 

Laravel  PHP  Laravel 9 
Author

Founder of CamboTutorial.com, I am happy to share my knowledge related to programming that can help other people. I love write tutorial related to PHP, Laravel, Python, Java, Android Developement, all published post are make simple and easy to understand for beginner. Follow him