<?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 simply access the first_name
attribute on a model instance:
$user = App\User::find(1);
$firstName = $user->first_name;
class User extends Model
{
public function setPasswordAttribute($password)
{
$this->attributes['password'] = bcrypt($password);
}
...
}
Above code does "bcrypting" each time password property is set.
$user = $users->first();
$user->password = 'white rabbit'; //laravel calls mutator on background
$user->save(); // password is bcrypted and one does not need to call bcrypt('white rabbit')