2016-11-23 4 views
1

コントローラではなく、モデルでデータを確認および編集できますか? たとえば、Modelからデータを取得し、コントローラでそれを処理します。Laravel 5.2 - モデル内のDBからデータを編集する

$user = User::select('name','privateflag','lastname')->get(); 
//name = John, privateflag = 1, lastname = Smith 
if ($user->privateflag == 1) {$user->lastname = 'Private';} 
//Pass to View: name = John, lastname = Private 

モデルでデータを確認および編集し、コントローラで既に更新されたデータを受信できますか?このように:

class User extends ... { 
... 
//Get from DB: name = John, privateflag = 1, lastname = Smith 
if ($user->privateflag == 1) {$user->lastname = 'Private';} 
//Pass to Controller: name = John, lastname = Private 
} 

答えて

3

推奨方法は、次のようにモデルでaccessorsを使用することです:

class User extends Model { 
... 
public function getLastNameAttribute() 
{ 
    if ($this->privateflag) { 
     return 'Private'; 
    } 
    return $this->attributes['lastname']; 
} 
+0

ありがとうございました!このデータを要求したControllerから関数の名前をアクセサに入れることは可能ですか? – Alex

関連する問題