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:
Route::get('/mutator ', 'demoController@mutator')->name('mutator');
php artisan make:controller demoController -mcr
public function mutator()
{
$User =User::find(1);
$User->name="kIraN";
$User->save();
}
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.