AccessorとMutatorがあるなんてC#っぽい。モデルをカプセル化するために積極的に使うといいかも。
Accessor
実装
<?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); } }
使い方
$user = App\User::find(1); $firstName = $user->first_name;
Mutator
実装
<?php namespace App; use Illuminate\Database\Eloquent\Model; class User extends Model { /** * Set the user's first name. * * @param string $value * @return string */ public function setFirstNameAttribute($value) { $this->attributes['first_name'] = strtolower($value); } }
使い方
$user = App\User::find(1); $user->first_name = 'Sally';
参考サイト
Eloquent: Mutators – Laravel – The PHP Framework For Web Artisans
http://laravel.com/docs/master/eloquent-mutators