从 Laravel 中的控制器返回多个 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44067351/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:00:05  来源:igfitidea点击:

Returning multiple JSON from controller in Laravel

jsonajaxlaravel

提问by prgrm

I have something like this in the route:

我在路线中有这样的事情:

Route::post('/iteminfo/{item_id}','itemcontroller@get_item_info');

And something like this in the controller

在控制器中类似这样的东西

public function get_item_info($request)
{
$item_image = Item_Image->where("item_id",$request)->first();
$item_something = Item_Something->where("item_id",$request)->first();
$item_more = Item_More->where("item_id",$request)->first();

return Response::json($item_image);

}

I want to return the 3 things but with return Response::json() I can only return 1 statement (as far as I know). Is there any way to return all of them?

我想返回 3 件事,但是使用 return Response::json() 我只能返回 1 个语句(据我所知)。有没有办法全部退回?

回答by Sandeesh

You can pass an array as the json response. So craft an array based on your data and use it.

您可以传递一个数组作为 json 响应。因此,根据您的数据制作一个数组并使用它。

return Response::json(array(
    'item_image' => $item_image,
    'item_something' => $item_something,
    'item_more' => $item_more,
));

回答by Clean code

Since it requires an Arrayparameter so you can construct an array from the variables

因为它需要一个Array参数,所以你可以从变量构造一个数组

 return response()->json(['item_image ' => $item_image, 'item_something' => $item_something, 'item_more' => $item_more  ]);
enter code here

Or

或者

return Resonse::json(['item_image ' => $item_image, 'item_something' => $item_something, 'item_more' => $item_more  ]);