
Eloquent Accessor Laravel
Eloquent accessor is important part for retrieve and set with some changing .
Accessor has two parts one is Accessor which retrieve with some change and another is Mutators which is set with some change.
For avoid confuse about accessor and mutator just look the picture .
Accessor:
Accessor function getFooAttribute
that means get the attribute of Foo which (Foo) is your table name .
public function getFirstNameAttribute($value)
{
return ucfirst($value);
}
Then return what do you change .
All those inside your model . if you want accessor for User model .
<?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);
}
}
Mutators:
Mutators set data with some changing . It uses setFooAttribute
public function setFirstNameAttribute($value)
{
$this->attributes['first_name'] = strtolower($value);
}
- If your table name as like first_name , your function will be
setFirstNameAttribute
<?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);
}
}
@code4mk