Laravel Accessor and Mutator Example

In this article, we will see laravel accessor and mutator examples. here we will see what is accessor and mutator, how to use the accessor and mutator with example. laravel mutator is used to set attribute, laravel accessor is used to get attribute in laravel, below I have added more information of accessor and mutator with example

So, let's see laravel 8 mutator, laravel 8 accessor, laravel accessor with parameter.

What are Accessors? 

Accessors create a dummy attribute on the object which you can access as if it were a database column. So, if your database has a user table and it has FirstName and LastName column and you need to get your full name then it will be like.

Syntax of Accessors :

get{Attribute}Attribute

Example :

public function getFullNameAttribute()
{
  return $this->FirstName. " " .$this->LastName;
}

After that, you can get the full user name with the below accessors.

{{ $user->full_name }}

 

 

What is Mutator?

Mutator is used to set the value of the attribute. A mutator transforms an Eloquent attribute value when it is set.

How to define a mutator,

set{Attribute}Attribute

above method on your model where {Attribute} is the "studly" cased name of the column you wish to access.

Example : 

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

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

Now you can use this in your controller.

use App\Models\Register;

$register= Register::find(1);

$register->name = 'Techsolutionstuff';

 


You might also like :

RECOMMENDED POSTS

FEATURE POSTS