Search code examples
phplaravelpaginationlaravel-10laravel-pagination

how to correctly show current data with laravel pagination?


I'm having trouble with pagination in Laravel 10. I have generated 13 data from my database and I'm on page 1, so I'm expecting to see something like

"Showing 1 to 8 of 13 results"

but instead, my code is displaying the message

"Showing 1 to 13 of 13 results"

what am I doing wrong? any help is appreciated.

this is my code:

    public function index(Request $request)
    {
        $client = new \GuzzleHttp\Client();

        $perPage = $request->query('per_page') ? : 8;
        $page = $request->query('page') ? : 1;

        $url = "http://localhost/api/culinary?page=$page&per_page=$perPage";

        $response = $client->request('GET', $url);

        $json = json_decode((string)$response->getBody(), true);

        $paginatedResult = new LengthAwarePaginator(
            $json, // the data to be paginated
            count($json), // total count of the data
            $perPage, // number of data shown per page
            $page, // current page number
        );

        $view_data = [
            'title' => 'Browse Culinary',
            'data' => $paginatedResult,
        ];
        return view('culinary.index', $view_data);
    }

and I'm using this code in the index.blade.php to show the pagination part

{{ $data->withQueryString()->withPath('/culinary')->links() }}

Solution

  • You should slice the items you pass to the paginator. From the docs:

    When manually creating a paginator instance, you should manually "slice" the array of results you pass to the paginator.

    So, pass this to your paginator:

    $offset = ($page - 1) * $perPage;
    
    $paginatedResult = new LengthAwarePaginator(
        array_slice($json, $offset, $perPage), // paginated data
        count($json), // total count of the data
        $perPage, // number of data shown per page
        $page, // current page number
    );