How to paginate with return as json laravel

rafitio picture rafitio · Dec 18, 2016 · Viewed 22.1k times · Source

I want to create a pagination with return as json, but I'm getting an error like below

ErrorException in Macroable.php line 74: Method links does not exist.

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() ?

Answer

Alexey Mezenin picture Alexey Mezenin · Dec 18, 2016

The Laravel paginator result classes implement the Illuminate\Contracts\Support\Jsonable Interface contract and expose the toJson method, so it's very easy to convert your pagination 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().