DEV Community

Techsolutionstuff
Techsolutionstuff

Posted on • Originally published at techsolutionstuff.com

3 1

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 :

Heroku

Deliver your unique apps, your own way.

Heroku tackles the toil — patching and upgrading, 24/7 ops and security, build systems, failovers, and more. Stay focused on building great data-driven applications.

Learn More

Top comments (0)

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, cherished by the supportive DEV Community. Coders of every background are encouraged to bring their perspectives and bolster our collective wisdom.

A sincere “thank you” often brightens someone’s day—share yours in the comments below!

On DEV, the act of sharing knowledge eases our journey and forges stronger community ties. Found value in this? A quick thank-you to the author can make a world of difference.

Okay