我可以在模型中检查和编辑数据,而不是在控制器中吗? 例如,现在我从Model获取数据并在Controller中使用它。
$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
我可以检查和编辑模型中的数据并在Controller中接收已更新的数据吗?像这样:
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
}
答案 0 :(得分:3)
推荐的方法是在模型中使用accessors,如下所示:
class User extends Model {
...
public function getLastNameAttribute()
{
if ($this->privateflag) {
return 'Private';
}
return $this->attributes['lastname'];
}