Hello Laravel Friends,
In this Laravel tutorial, we will learn about Accessors and Mutators in Laravel. We will also go through the examples to understand the concept of how to use Accessors and Mutators in Laravel.
So let’s see Laravel 8 Accessor and Laravel 8 Mutator with examples.
What are Accessors and Mutators in Laravel?
Basically, Laravel Accessors and Mutators are custom, user-defined methods. Accessors and mutators are used to format Eloquent attributes when retrieving them from a model or setting their value.
Accessors are used to alter the attributes when you retrieve them from the database. Whereas, Mutators are used to alter the attributes before saving them to the database.
Accessors
To define an accessor, create a get{Attribute_name}Attribute method on your model where Attribute_name is the name of the column you wish to access.
For example, we are creating a method getCreatedAtAttribute() for casting a created_at dateTime attribute of the Comment Model in human-readable form.
Add the below code to the model
path – App/Model/Comment
1 2 3 4 5 6 7 8 9 10 |
/** * Get the comment create time in human-readable form. * * @param datetime $value * @return string */ public function getCreatedAtAttribute($value) { return Carbon::parse($value)->diffForHumans([ 'parts' => 1]); } |
How to use > Comment::find(1)->created_at;
Model code – Your comment model looks like this
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
<?php namespace App\Models; use Carbon\Carbon; use Carbon\CarbonInterface; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Comment extends Model { use HasFactory; /** * The attributes that are mass assignable. * * @var array<int, string> */ protected $fillable = [ 'comment', 'user_id', 'post_id', ]; /** * Get the comment create time in human-readable form. * * @param datetime $value * @return string */ public function getCreatedAtAttribute($value) { return Carbon::parse($value)->diffForHumans(['syntax' => CarbonInterface::DIFF_ABSOLUTE]); } } |
Output
1 |
// 6 months ago |
Mutator
To define a mutator, define a set{Attribute_name}Attribute method on your model where Attribute_name is the name of the column you wish to access.
For example, we are creating a method setFirstNameAttribute() for the first_name attribute of the User Model to store value in lowercase.
Path – App/Model/User
1 2 3 4 5 6 7 8 9 10 |
/** * Set the user's first name. * * @param string $value * @return void */ public function setFirstNameAttribute($value) { $this->attributes['first_name'] = strtolower($value); } |
How to use >
1 2 3 4 5 6 7 |
$user = User::create([ 'first_name' => "MageComp", "last_name" => "LLP", "email" => "mailto:magecomp@mail.com", "password" => Hash::make("password") ]); return $user; |
The user Model Looks like this
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
<?php namespace App\Models; use Carbon\Carbon; use Carbon\CarbonInterface; 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; class User extends Authenticatable { use HasApiTokens, HasFactory, Notifiable; /** * The attributes that are mass assignable. * * @var array<int, string> */ protected $fillable = [ 'first_name', 'last_name', 'email', 'password', ]; /** * The attributes that should be hidden for serialization. * * @var array<int, string> */ protected $hidden = [ 'password', 'remember_token', ]; /** * The attributes that should be cast. * * @var array<string, string> */ protected $casts = [ 'email_verified_at' => 'datetime', ]; /** * Set the user's first name. * * @param string $value * @return void */ public function setFirstNameAttribute($value) { $this->attributes['first_name'] = strtolower($value); } } |
Output
1 2 3 4 5 6 7 8 9 |
// { // "id":1, // "first_name":"magecomp", // to lowercase // "last_name":"LLP", // "mailto:email":"magecomp@mail.com", // "email_verified_at":"2023-03-09T10:09:10.000000Z", // "created_at":"2022-03-09T10:09:10.000000Z", // "updated_at":"2022-03-09T05:24:33.000000Z" // } |
Conclusion:
This was all about Accessors and Mutators in Laravel. Accessors and Mutators provide a great way to alter data before it’s saved or retrieved from a database.
If you are looking to expand your knowledge in Laravel, check out some of the important Laravel tutorials that will help you learn deeply about Laravel.
Share this guide on Accessors and Mutators in Laravel with your friends to help them learn about these concepts.
Happy Coding!