如何使用返回为 json laravel 进行分页
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41209422/
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
How to paginate with return as json laravel
提问by rafitio
I want to create a pagination with return as json, but I'm getting an error like below
我想创建一个返回为 json 的分页,但出现如下错误
ErrorException in Macroable.php line 74: Method links does not exist.
Macroable.php 第 74 行中的 ErrorException:方法链接不存在。
here my controller code
这是我的控制器代码
public function getcustomer($id){
$customer = Customer::find($id)->paginate(5);
return response()->json([$customer], 200);
}
and here my blade code
这是我的刀片代码
{{$customer->links('vendor.pagination.pagination')}}
how can I create a pagination with json response() ?
如何使用 json response() 创建分页?
采纳答案by Alexey Mezenin
The Laravel paginator result classes implement the
Illuminate\Contracts\Support\Jsonable
Interface contract and expose thetoJson
method, so it's very easy to convert your pagination results to JSON.
Laravel 分页器结果类实现了
Illuminate\Contracts\Support\Jsonable
接口协定并公开了toJson
方法,因此将分页结果转换为 JSON 非常容易。
https://laravel.com/docs/5.3/pagination#converting-results-to-json
https://laravel.com/docs/5.3/pagination#converting-results-to-json
If you want to build links, you should do it manually. Or you should return pagination as usual and use render()
method to build links and create copy of pagination object to convert it to JSON with toJson()
.
如果你想建立链接,你应该手动完成。或者您应该像往常一样返回分页并使用render()
方法来构建链接并创建分页对象的副本以将其转换为 JSON toJson()
。
回答by Intergalactisch
I'm running in the same issue as mentioned above and am curious how you've solved it in the end.
我遇到了与上述相同的问题,并且很好奇您最终是如何解决它的。
In my case I'm doing an API-request which gets the following decoded result:
在我的例子中,我正在做一个 API 请求,它得到以下解码结果:
{#388 ▼
+"total": 699
+"per_page": 50
+"current_page": 1
+"last_page": 14
+"next_page_url": "API_URL?page=2"
+"prev_page_url": null
+"from": 1
+"to": 50
+"data": array:50 [?]
}
And in my blade template:
在我的刀片模板中:
{{ $products->links() }}
In my blade template it says that the links method doesn't exist, probably due to the structure of the JSON. How do I build my links manually, e.g. with render()?
在我的刀片模板中,它说 links 方法不存在,可能是由于 JSON 的结构。我如何手动构建我的链接,例如使用 render()?