How to get and set Mutators Attributs in laravel ?
Mutators allow you to format attribute value when you retrieve or set them on model instances. for example when you retrieve name value of database to show and you need to show first letter capital so getNameAttribute function can do it for all of call.
Define a Mutators:-
To define mutators setFieldNameAttribute on your model when you try to save value of the this field automatically value has changed according to mutators
<?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 setFirstNameAttribute($value)
{
$this->attributes['first_name'] = strtolower($value);
}
}
To define accessor getFieldNameAttribute on your model when you try to save value of the this field automatically value has changed according to mutators
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* Get the user's first name.
*
* @param string $value
* @return string
*/
public function getFirstNameAttribute($value)
{
return ucfirst($value);
}
}
Post a Comment