DEV Community

Websolutionstuff
Websolutionstuff

Posted on • Originally published at websolutionstuff.com

Laravel Accessor and Mutator Example

In this post we will see laravel accessor and mutator example, here we will see what is accessor and mutator, how to use 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

What is 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 user table and it has FirstName and LastName coloumn and you need to get full name then it will be like.

Syntax of Accessors :

get{Attribute}Attribute
Enter fullscreen mode Exit fullscreen mode

Example :

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

After that you can get full user name with below Accessors.

{{ $user->full_name }}
Enter fullscreen mode Exit fullscreen mode

What is Mutator ?

Mutator is use to set value of attribute, A mutator transforms an Eloquent attribute value when it is set.

How to define a mutator,

set{Attribute}Attribute
Enter fullscreen mode Exit fullscreen mode

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);
    }
}
Enter fullscreen mode Exit fullscreen mode

Now you can use this in your controller like.

use App\Models\Register;

$register= Register::find(1);

$register->name = 'Websolutionstuff';
Enter fullscreen mode Exit fullscreen mode

Read More : jQuery Image Magnifier on Mouse Hover


Read More : Laravel 8 Socialite Login with Google Account


Read More : Stripe Payment Gateway Integration Example In Laravel 8


Thanks for the reading...!!

Discussion (0)