Eloquent Mutators in Laravel are used to modify the values of attributes when retrieving or setting them on Eloquent model instances. They allow you to define custom logic to automatically transform attribute values before they are saved to the database or accessed by your application.
Step 1: Install Laravel App
composer create-project laravel/laravel example-EloquentMutators
Step 2: Migration and Model
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');
}
};
Run migration
php artisan migrate
Update Model
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
php artisan make:controller UserController
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
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:
php artisan serve
Now, Go to web browser, type the given URL and see the output:
http://localhost:8000/create-user