AccessorとMutatorがあるなんてC#っぽい。モデルをカプセル化するために積極的に使うといいかも。
Accessor
実装
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?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); } } |
使い方
1 2 |
$user = App\User::find(1); $firstName = $user->first_name; |
Mutator
実装
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?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); } } |
使い方
1 2 |
$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