Php Laravel/Vue-将数据:Json嵌套值作为字符串传递
我试图将一个JSON对象从我的Laravel后端传递到我的Vue前端,但其中一个嵌套属性将作为字符串而不是对象返回。所讨论的对象是Php Laravel/Vue-将数据:Json嵌套值作为字符串传递,php,json,laravel,vue.js,Php,Json,Laravel,Vue.js,我试图将一个JSON对象从我的Laravel后端传递到我的Vue前端,但其中一个嵌套属性将作为字符串而不是对象返回。所讨论的对象是user.options,如下所示 user.options对象格式良好,但当我发送响应时,它被视为字符串。我可以在前端将字符串转换为JSON,但这并不理想 不需要手动序列化属性的JSON。相反,您可以使用Eloquent的$casts属性定义您的选项应被视为对象: class User { /** * The attributes that sh
user.options
,如下所示
user.options
对象格式良好,但当我发送响应时,它被视为字符串。我可以在前端将字符串转换为JSON,但这并不理想
不需要手动序列化属性的JSON。相反,您可以使用Eloquent的
$casts
属性定义您的选项应被视为对象:
class User
{
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'options' => 'object',
];
}
然后可以将数组和对象指定给此属性。Eloquent将在后台将其存储为JSON。检索属性时,Eloquent将再次将其转换回对象:
public function update(Request $request) {
$user = $this->user;
$user->options = [
'cart' => $request->only('product_id', 'code', 'product_slug', 'pic_url', 'request')
];
$user->save();
return response()->json($user);
}
public function update(Request $request) {
$user = $this->user;
$user->options = [
'cart' => $request->only('product_id', 'code', 'product_slug', 'pic_url', 'request')
];
$user->save();
return response()->json($user);
}