Eloquent: Mutators
Introduction
Accessors and mutators 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 and mutators, Eloquent can also automatically cast date fields to Carbon instances or even cast text fields to JSON.
Accessors & Mutators
Defining An Accessor
To define an accessor, create a getFooAttribute
method on your model where Foo
is the "studly" cased name of the column you wish to access. In this example, we'll define an accessor for the first_name
attribute. The accessor will automatically be called by Eloquent when attempting to retrieve the value of the first_name
attribute:
<?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);
}
}
As you can see, the original value of the column is passed to the accessor, allowing you to manipulate and return the value. To access the value of the accessor, you may access the first_name
attribute on a model instance:
$user = App\User::find(1);
$firstName = $user->first_name;
Of course, you may also use accessors to return new, computed values from existing attributes:
/**
* Get the user's full name.
*
* @return string
*/
public function getFullNameAttribute()
{
return "{$this->first_name} {$this->last_name}";
}