Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Laravel/Vue-将数据:Json嵌套值作为字符串传递_Php_Json_Laravel_Vue.js - Fatal编程技术网

Php Laravel/Vue-将数据:Json嵌套值作为字符串传递

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

我试图将一个JSON对象从我的Laravel后端传递到我的Vue前端,但其中一个嵌套属性将作为字符串而不是对象返回。所讨论的对象是
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);
}