Laravel Accessors and Mutators

Laravel Accessors and Mutators

Accessors and Mutators are very useful when you are about to change some value before showing it or change the value before saving it. This article will practically demonstrate how Accessors and Mutators works.

You can read more about from the Laravel Official Docs What are Accessors and Mutators.

Accessors – Laravel Accessors and Mutators

Accessors means you can access a field but make some changes before accessing it and to show it.

Let say we have a model User and we have two fields FirstName and LastName like

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
     protected $fillable = ['FirstName', 'LastName'];
}

There are two fields and they are accessible separately but what if you want to show full name. You can do it by just concatenating them on the blade but that would be not a practical way.
So we write an Accessor on the Eloquent level like,

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    protected $fillable = ['FirstName', 'LastName'];


    /**
     * Get the user's full name.
     *
     * @param  string  $value
     * @return string
     */
    public function getFullNameAttribute()
    {
        return $this->FirstName . ' ' . $this->LastName;
    }

}

You can access the Full name on the view as,

@foreach($users as $user)
    {{ $user -> full_name }}
@endforeach

Mutators – Laravel Accessors and Mutators

Mutator is the modificator which modifies the values before saving to the database.

For example we want to save the first letter of FirstName and LastName as capital in the database then mutator can help to do this like,

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    protected $fillable = ['FirstName', 'LastName'];


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


    /**
     * Set the user's last name first letter to capital.
     *
     * @param  string  $value
     * @return void
     */
    public function setLastNameAttribute($value)
    {
        $this->attributes['last_name'] = ucfirst($value);
    }

}

Previous Post
Next Post

Comments

Avatar for Cryptocurrency Prices
Cryptocurrency Prices

I have read your article carefully and I agree with you very much. This has provided a great help for my thesis writing, and I will seriously improve it. However, I don’t know much about a certain place. Can you help me?

Leave a Reply

Your email address will not be published. Required fields are marked *