Laravel 9 Eloquent Mutators and Accessors Example Tutorial
Hi Dev,
This article will provide example of Laravel 9 Eloquent Mutators and Accessors Example Tutorial. if you want to see example of Eloquent: Mutators & Casting Laravel 9 then you are a right place. We will look at example of Eloquent Mutators and Accessors in Laravel 9 Tutorial. it's simple example of Eloquent Accessors and Mutators in Laravel 9
This article will give you simple example of Accessors and Mutators in Laravel 9 Eloquent
"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.
Let's start following example:
Step 1: Install LaravelFirst of all we are going from scratch new laravel application. if you have already created the project, then skip following step.
composer create-project laravel/laravel example-appStep 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' => '[email protected]', '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 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 steps have been done, now you have to type the given command and hit enter to run the laravel app:
php artisan serveOutput 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:

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" => "[email protected]" "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...