2016-11-23 52 views
1

我可以在模型中而不是在控制器中檢查和編輯數據嗎?例如,現在我從Model中獲取數據並在Controller中使用它。Laravel 5.2 - 編輯模型中來自數據庫的數據

$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