Laravel

What are Accessors and Mutators in Laravel? Learn How to Use Them

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

/**
     * 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 

<?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

// 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

/**
     * Set the user's first name.
     *
     * @param  string  $value
     * @return void
*/public function setFirstNameAttribute($value)
{
        $this->attributes['first_name'] = strtolower($value);
}

How to use > 

$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 

<?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 

// {
//     "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!

Click to rate this post!
[Total: 3 Average: 4.3]
Bharat Desai

Bharat Desai is a Co-Founder at MageComp. He is an Adobe Magento Certified Frontend Developer 🏅 with having 8+ Years of experience and has developed 150+ Magento 2 Products with MageComp. He has an unquenchable thirst to learn new things. On off days you can find him playing the game of Chess ♟️ or Cricket 🏏.

Recent Posts

How to Integrate ChatGPT with Laravel Application?

In this guide, we'll explore how to integrate ChatGPT, an AI-powered chatbot, with a Laravel…

3 days ago

What are Net Sales? How to Calculate Your Net Sales?

In the world of business, understanding financial metrics is crucial for making informed decisions and…

5 days ago

Magento 2 Extensions Digest April 2024 (New Release & Updates)

Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…

5 days ago

The ABCs of Geofencing: Definition, Features and Uses

In this era, businesses are always on the lookout for ways to engage with their…

6 days ago

How to Delete Product Variant in a Shopify Remix App using GraphQL Mutations?

Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…

7 days ago

6 Innovative Tools Revolutionizing E-Commerce Operations

E-commerce has transformed the way consumers shop for products and services and interact with businesses.…

1 week ago