esmaill23's avatar

pagination without eloquent

i need to paginate response that return from another web service to show in my service.

public function index()
    {
        $client = new Client();
        $crashes = $client->request('GET', 'http://localhost:8000/crashes')->getBody()->getContents();
        return view('crashes', ['crashes' => json_decode($crashes)]);
    }

in this code i get a json response from another service and i want to paginate it to show in my view. how ?

0 likes
3 replies
Borisu's avatar
Borisu
Best Answer
Level 37

You can use the Paginator class. Something like this:

$slicedCrashes = array_slice($crashes, (request('page') ? request('page') - 1 : 0) * $perPage, $perPage);
return new LengthAwarePaginator(
            $slicedCrashes,
            count($crashes),
            $perPage,
            request('page'),
            ['path' => url()->current()]
        );

LengthAwarePaginator accepts the result subset (slicedCrashes), the total count, the amount of results per page, the current page, and an array of options. In the options array you only have to make sure that the url is correct, in order to build the links correctly. Then you can use the results as a normal paged Eloquent model.

esmaill23's avatar

thank you. it work but in my code every time i must request to webservice in every page ?

Please or to participate in this conversation.