Today now in this post i will give you an examples of laravel 9 mutator and accessor with the examples. Here we will learn laravel 9 accessors and mutators examples. I will teach mutators and accessors in laravel 9. We will learn what is mutator in laravel 9. Here i will do the following things for the laravel 9 eloquent getter and setter example.
We know that Laravel provides the Accessors and Mutators in Eloquent. At First of all, here I will give you a simple definition of what is Accessors and Mutators in the Laravel Eloquent, Then here I will give you a very simple example where we will understand what it works.
“Accessors is create the custom attribute on the object which i can access as if it were in a database column.”
“Mutator is a way to change the data when it is going to set into database table.”
So, let’s start and see the bellow example and we will got it how it works.
Step 1: Install Laravel 9
This is first step , this step is not needed if you are already install before. However, if you do not created the laravel application, then we may go ahead and execute the below command:
composer create-project laravel/laravel example-app
Step 2: Update Migration and Model
Here, I will update the migration with the adding new column date_of_birth forthe “users” table, let’s update the code on following file.
<?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, need to run this for create new migration by using laravel migration command as bellow:
php artisan migrate
Now i 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
Now in this step, i will create a new controller as name UserController; now in this file, i will add two method one is create() and another one is show() for creating the new record and other’s one for show record from the database.
Let’s create the UserController by following command:
php artisan make:controller UserController
next, let’s need to update the following code to the 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' => 'srsagor',
'email' => 'srsagor007@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, i need to open and need to 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');
});
Read Also: How To Implement Laravel 9 form validation ?
Thanks for read. I hope it help you. For more you can follow us on facebook