Laravel 9 Eloquent Mutators and Accessors Example
In this post, we will give you information about Laravel 9 Eloquent Mutators and Accessors Example. Here we will give you detail about Laravel 9 Eloquent Mutators and Accessors Example And how to use it also give you a demo for it if it is necessary.
Laravel provides Accessors and Mutators in Eloquent. First of all, we will give you a simple definition of what is Accessors and Mutators in Laravel Eloquent, Then we 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, we 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 to show the 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 inserting and before getting data using Accessors and Mutators.
So, let’s see the below example and you will get 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 by adding a new column date_of_birth for the “users” table, let’s update the code on the following file.
database/migrations/2022_02_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 the User model by using the 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 methods create() and show() for creating new record and showing records from a 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' => 'jon', 'email' => 'jon@gmail.com', 'password' => bcrypt('555544555'), 'date_of_birth' => '07/21/1995' ]; $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; 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 a user as like the bellow screenshot:
Output for Accessor:
http://localhost:8000/get-user
It will create a user as like bellow screenshot:
array:7 [ "id" => 1 "name" => "JON" "email" => "jon@gmail.com" "email_verified_at" => null "date_of_birth" => "07/21/1995" "created_at" => "2022-02-12T04:37:46.000000Z" "updated_at" => "2022-02-12T04:37:46.000000Z" ]
Conclusion for Laravel 9 Eloquent Mutators and Accessors Example
Hope this code and post will help you implement Laravel 9 Eloquent Mutators and Accessors Example. if you need any help or any feedback give it in the comment section or you have a good idea about this post you can give it in the comment section. Your comment will help us to help you more and improve us.