Aar*_*ron 2 php json laravel laravel-4
我们将用户首选项存储为JSON.由于我们的应用程序充当API,因此响应也以JSON形式返回,但首选项字段以字符串形式返回.我想确保在发送任何响应之前,对象的这一部分始终被解码,即
$user->prefs = json_decode($user->prefs);
Run Code Online (Sandbox Code Playgroud)
但是哪里?我应该看看"重载"用户索引方法吗?这更像是一个before_filter动作吗?什么是laravel这样做的方式?
在您的模型上使用Eloquent访问器:
public function getPreferencesAttribute($value)
{
return json_decode($value);
}
Run Code Online (Sandbox Code Playgroud)
然后你只需要:
$user = User::find($id);
return $user->preferences;
Run Code Online (Sandbox Code Playgroud)
查看文档:http://laravel.com/docs/eloquent#accessors-and-mutators
| 归档时间: |
|
| 查看次数: |
1414 次 |
| 最近记录: |