Laravel Mutators

Laravel Mutators

Accessors & Mutators

Allow you to format Eloquent attribute values when you retrieve or set them on model instances.

Date Mutators

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * The attributes that should be mutated to dates.
     *
     * @var array
     */
    protected $dates = [
        'created_at',
        'updated_at',
        'deleted_at'
    ];
}
$user = App\User::find(1);

$user->deleted_at = now();

$user->save();
$user = App\User::find(1);

return $user->deleted_at->getTimestamp();

Attribute Casting

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'is_admin' => 'boolean',
    ];
}
$user = App\User::find(1);

if ($user->is_admin) {
    //
}

Laravel Mutators — Structure map

Clickable & Draggable!

Laravel Mutators — Related pages: