Laravel 9 Eloquent Mutators and Accessors Example
Hi Dev,
This post will give you examples of laravel 9 mutator and accessor examples. Here you will learn laravel 9 accessors and mutators examples. you will learn mutators and accessors in laravel 9. you will learn what is mutator in laravel 9. you will do the following things for laravel 9 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 what 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.
So, let's see bellow example and you will got it how it works.
Step 1: Install Laravel 9
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...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Laravel 9 Multiple Image Upload Tutorial
- Laravel 9 File Upload Tutorial Example
- Laravel 9 Image Upload Example Tutorial
- Laravel 9 Form Validation Tutorial Example
- Laravel 9 CRUD Application Tutorial Example
- How to Add Password Protection for PDF File in Laravel?
- Laravel Sum Query with Where Condition Example
- Laravel Group By with Min Value Query Example
- Laravel Connect Remote Database using SSH Tunnel Example
- Laravel CRUD with Image Upload Tutorial