What is Accessors And Mutators in Laravel 9?

Sometimes need to modify a field value while retrieving records using Laravel Eloquent e.g. get date from datetime field, make field value in upper case, etc.

To do that you can either use selectRaw() or Accessors.

Similarly, If you want to update the value while inserting or updating using Eloquent then you can either modify value every time before storing or use Mutators.

In this tutorial, I show how you can use Accessors And Mutators in the Laravel 9 project.

What is Accessors And Mutators in Laravel?


Contents

  1. Model
  2. Create and Use Accessors
  3. Create and Use Mutators
  4. Output
  5. Conclusion

1. Model

In the example, I am using Employees Model for explaining Accessors And Mutators –

Completed Code

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Employees extends Model
{
     use HasFactory;
     protected $fillable = [
           'emp_name','email','city','gender','status'
     ];

}

2. Create and Use Accessors

  • Accessors are used to modify the field value while retrieving.
  • It is automatically called when you try to read a record using Eloquent.

Define Accessor –

  • Open a Model where you want to define Accessors.
  • Include –
use Illuminate\Database\Eloquent\Casts\Attribute;
  • Now create a protected method for the attribute with Attribute return type. Here, I am modifying emp_name response. When read emp_name value then it will convert the first character to upper case.
protected function empName(): Attribute
{
     return Attribute::make(
           get: fn ($value) => ucfirst($value)
     );
}
  • Similarly, modify created_at value. It will return Date when read.
protected function createdAt(): Attribute
{
     return Attribute::make(
           get: fn ($value) => Carbon::parse($value)->format('Y-m-d'),
     );
}

Model  –

After modification Employees Model look like this –

Completed Code

<?php

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Casts\Attribute;

class Employees extends Model
{
     use HasFactory;
     protected $fillable = [
           'emp_name','email','city','gender','status'
     ];

     protected function empName(): Attribute
     {
           return Attribute::make(
                get: fn ($value) => strtolower($value)
           );
     }

     protected function createdAt(): Attribute
     {
           return Attribute::make(
                get: fn ($value) => Carbon::parse($value)->format('Y-m-d'),
           );
     }
}

Controller

You do not need to execute any extra steps. Eloquent automatically applies Accessors if defined for a field while reading.

In the Model defined Accessors for emp_name and created_at fields.

Values automatically get formatted when reading.

Completed Code

<?php

namespace App\Http\Controllers;

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

class PagesController extends Controller
{
      public function index(){

           $record = Employees::find(1);

           $emp_name = $record->emp_name;
           $created_at = $record->created_at;

           echo "Name : ".$emp_name."<br>";
           echo "Created At : ".$created_at."<br>";
           die;
      }
}

It will return following output when read –

Name : Yogesh
Created At : 2022-10-23

3. Create and Use Mutators

  • Mutators are used to modify the value while inserting or upgrading.
  • It is also automatically called by Eloquent.

Define Mutators –

  • Open a Model where you want to define Mutators.
  • Include –
use Illuminate\Database\Eloquent\Casts\Attribute;
  • Defining Mutator on the same method where Accessor is also defined for emp_name field. It will convert the value to lowercase before storing.
protected function empName(): Attribute
{
     return Attribute::make(
          get: fn ($value) => ucfirst($value),
          set: fn ($value) => strtolower($value),
     );
}
  • Also, modifying city field. It will convert the passed value to upper case before storing.
protected function city(): Attribute
{
     return Attribute::make(
         set: fn ($value) => strtoupper($value),
     );
}

Model –

After modification Employees Model looks like this –

Completed Code

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Casts\Attribute;

class Employees extends Model
{
      use HasFactory;
      protected $fillable = [
           'emp_name','email','city','gender','status'
      ];

      protected function empName(): Attribute
      {
           return Attribute::make(
                get: fn ($value) => ucfirst($value),
                set: fn ($value) => strtolower($value),
           );
      }

      protected function city(): Attribute
      {
           return Attribute::make(
                set: fn ($value) => strtoupper($value),
           );
      }

}

Controller –

Mutator automatically applies when you insert/update a record using Eloquent.

Completed Code

<?php

namespace App\Http\Controllers;

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

class PagesController extends Controller
{
     public function index(){

         Employees::create([
             'emp_name' => 'Akshay singh', 
             'email' => 'akshay@makitweb.com',
             'city' => 'Delhi',
             'gender' => 'Male',
             'status' => 1,
         ]);

     }
}

4. Output

View Output


5. Conclusion

Accessors And Mutators are defined in the Model. Using this you can modify the field value while retrieving and storing.

If you found this tutorial helpful then don't forget to share.

Leave a Comment