What Is The Use Of Mutator In Laravel With Example

admin_img Posted By Bajarangi soft , Posted On 10-09-2020

Mutator allow you to format Eloquent attribute values when you retrieve or set them on model instances. For example, you may want to use the Laravel encrypter to encrypt a value while it is stored in the database, and then automatically decrypt the attribute when you access it on an Eloquent model. In addition to custom accessors, Eloquent can also automatically cast date fields to Carbon instances or even cast text fields to JSON.

What Is The Use Of Mutator In Laravel With Example

Defining A Mutator

To define a mutator, define a setFooAttribute method on your model where Foo is the "is name which is given in database" cased name of the column you wish to access. So, again, let's define a mutator for the name attribute. This mutator will be automatically called when we attempt to set the value of the name attribute on the model:

Open User.php model file

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

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


The mutator will receive the value that is being set on the attribute, allowing you to manipulate the value and set the manipulated value on the Eloquent model's internal $attributes property.

So, for example, if we attempt to set the name attribute to Kiran:

Create Route in Web.php file as below
Route::get('/mutator ', 'demoController@mutator')->name('mutator');


Create demoController and implement code to set the name in upper case
php artisan make:controller demoController -mcr


open demoController.php in app\Http\Controller folder and implement code as below
public function mutator()
    {

        $User =User::find(1);
        $User->name="kIraN";
        $User->save();
    }


In this example, the setNameAttribute function will be called with the value KIRAN. The mutator will then apply the strtoupper function to the name and set its resulting value in the internal $attributes array.

Related Post