Laravel 10 Eloquent Mutators and Accessors Example

By Hardik Savani November 6, 2023 Category : Laravel

Hello Dev,

Hello, all! In this article, we will talk about laravel 10 mutator and accessor example. We will use laravel 10 accessors and mutators example. This article will give you a simple example of mutators and accessors in laravel 10. we will help you to give an example of what is mutator in laravel 10. follow the below step for laravel 10 eloquent getter and setter example.

Laravel provides Accessors and Mutators in Eloquent. First of all, I will give you a simple definition of what is Accessors and Mutators in Laravel Eloquent, Then I will give you a very simple example where you will understand how it works.

"Accessors create a custom attribute on the object which you can access as if it were a database column."

"Mutator is a way to change data when it is going set into database table."

Now, I will explain to you by a simple example. if we have a field called "date of birth" with date datatype in the user model. You will give the user to input the date of birth in "m/d/Y" format, but the database accepts "Y-m-d" then you always change the date format before inserting the record into a database. The same thing when you retrieve records from the database then you have show date "m/d/Y" to the user. so it might be multiple places you have to create records and show data, then you have to do the same thing again and again. laravel provides a solution for that to automatically change the value before insert and before getting data using Accessors and Mutators.

Step for Laravel Accessor and Mutator Example

  • Step 1: Install Laravel 10
  • Step 2: Update Migration and Model
  • Step 3: Create Controller
  • Step 4: Create and Add Routes
  • Run Laravel App

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

Step 1: Install Laravel 10

This step is not required; however, if you have not created the laravel app, then you may go ahead and execute the below command:

composer create-project laravel/laravel example-app

Step 2: Update Migration and Model

Here, we will update migration with adding new column date_of_birth for "users" table, let's update code on following file.

database/migrations/2014_10_12_000000_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->date('date_of_birth');

$table->rememberToken();

$table->timestamps();

});

}

/**

* Reverse the migrations.

*

* @return void

*/

public function down()

{

Schema::dropIfExists('users');

}

};

Next, run create new migration using laravel migration command as bellow:

php artisan migrate

Now we will update User model by using following command:

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',

'date_of_birth'

];

/**

* 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 dateOfBirth(): Attribute

{

return new Attribute(

get: fn ($value) => Carbon::parse($value)->format('m/d/Y'),

set: fn ($value) => Carbon::parse($value)->format('Y-m-d'),

);

}

}

Step 3: Create Controller

In this step, we will create a new UserController; in this file, we will add two method create() and show() for creating new record and show record from database.

Let's create UserController by following command:

php artisan make:controller UserController

next, let's update the following code to Controller File.

app/Http/Controllers/UserController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\User;

class UserController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function create()

{

$input = [

'name' => 'Hardik',

'email' => 'hardik2@gmail.com',

'password' => bcrypt('123456'),

'date_of_birth' => '07/21/1994'

];

$user = User::create($input);

dd($user);

}

/**

* Write code on Method

*

* @return response()

*/

public function show()

{

$user = User::first();

dd($user->toArray());

}

}

Step 4: Create and Add Routes

Next, You have to open and update the following routes in the routes/web.php 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::controller(UserController::class)->group(function(){

Route::get('create-user', 'create');

Route::get('get-user', 'show');

});

Run Laravel App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:

php artisan serve

Output for Mutator:

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:8000/create-user

It will create user as like bellow screen shot:

Output for Accessor:

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:8000/get-user

It will create user as like bellow screen shot:

array:7 [

"id" => 1

"name" => "Hardik"

"email" => "hardik@gmail.com"

"email_verified_at" => null

"date_of_birth" => "07/21/1994"

"created_at" => "2022-02-11T04:37:46.000000Z"

"updated_at" => "2022-02-11T04:37:46.000000Z"

]

I hope it can help you...

Shares