Laravel Accessor and Mutator Example

Websolutionstuff | Mar-16-2021 | Categories : Laravel

In this article, we will see the laravel accessor and mutator example. Here, we will learn what is accessor and mutator and how to use an accessor and mutator in laravel 6, laravel 7, laravel 8, and laravel 9.

laravel mutator is used to set attributes and laravel accessor is used to get attributes in laravel 7/8/9. below I have added more information about the accessor and mutator with an example.

So, let's see the laravel 7/8/9 mutator and laravel 7/8/9 accessor.

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 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 names 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 = 'Websolutionstuff';

 


You might also like:

Recommended Post
Featured Post
How To Change Datepicker Start Date In Angular 15
How To Change Datepicker Start...

In this tutorial, I will guide you through the process of changing the start date of a datepicker component in Angular 1...

Read More

Jul-03-2023

How To Create Dependent Dropdown In Laravel
How To Create Dependent Dropdo...

In this article, we will see how to create a dependent dropdown list in laravel using ajax. Many times we have requ...

Read More

Jul-05-2020

Laravel 8 Left Join Query Example
Laravel 8 Left Join Query Exam...

In this tutorial I will give you laravel 8 left join query example. laravel left join eloquent returns all rows from the...

Read More

Nov-26-2021

Laravel 9 Group Column Chart Using Highcharts
Laravel 9 Group Column Chart U...

In the world of web development, Laravel 9 is a user-friendly PHP framework. When combined with Highcharts, a top JavaSc...

Read More

Jan-02-2023