[英]Use the return value of response->json response in the backend
[英]Laravel response->json() corrupts valid json?
我认为这是一件非常简单的事情,但我不知道如何去做。 我所做的基本上是这样的:
$ads= Ad::query()->select(['category_id', 'title', 'start_date'])->where(['account_id'=>$id])->get();
$ads= json_encode($ads);
return response()->json($ads, 200);
这样做的结果是:
"[{"category_id":1,"title":"Scacchi","start_date":1517982647},{"category_id":1,"title":"test test test","start_date":null}]"
这是一个字符串而不是有效的 json,因为外部引号是由 json() 函数添加的,因为 json_encode 之后的 $ads 是有效的 json。
我怎样才能防止这种奇怪的行为?
直接返回即可;
$ads= Ad::query()->select(['category_id', 'title', 'start_date'])->where(['account_id'=>$id])->get();
return $ads;
它应该是 json ,
UDPATE:
使用响应 json,执行以下操作:
return response()->json([
'data' => $ads
]);
response->json() 函数内部应该有一个数组,因此,您应该将结果转换为数组并将其传递给响应。
$ads= Ad::query()->select(['category_id', 'title', 'start_date'])->where(['account_id'=>$id])->get()->toArray( );
返回 response()->json($ads, 200);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.