DEV Community 👩‍💻👨‍💻

Techsolutionstuff
Techsolutionstuff

Posted on • Originally published at techsolutionstuff.com

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
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 the full user name with the below accessors.

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

Read Also : Laravel 8 Form Class Not Found


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

use App\Models\Register;

$register= Register::find(1);

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

You might also like :

Top comments (0)

🌚 Browsing with dark mode makes you a better developer by a factor of exactly 40.

It's a scientific fact.