Home > front end >  Laravel "page" query string parameter ignored in API when trying to use pagination
Laravel "page" query string parameter ignored in API when trying to use pagination

Time:09-23

I have this endpoint where I want to utilize pagination:

public function list() {
    return Cache::remember('list_albums_'.App::getLocale(), 60, function () {
        return Album::with(['group', 'event', 'event.translation'])
            ->orderBy('id', 'desc')
            ->simplePaginate(12);
    });
}

However, the same 12 results are always returned. The network request shows that ?page=X is being sent, but the response is always identical.

Route:

Route::get('/albums/{page?}', 'AlbumController@list');

CodePudding user response:

When using Laravel's caching, even if the contained code is reactive to the parameters being passed, such as Laravel's Pagination automatically paging based on the including of ?page=X, Caching will override that, unless the cache is "Busted" (i.e. by using a unique Cache Key, such as 'list_albums_' . App::getLocale() . request()->input('page')).

Since Pagination is already designed as a method to improve loading by "chunking" results into smaller portions, doubling-up on Caching, which is designed to increase loading times by not having to reload things can be redundant, especially for small page sizes like 12. For 100s or 1000s of results, tacking on this request()->input('page') would make sense, but for 12, it would just end up bloating your cache.

In this instance, it's probably best to simply remove caching, and allow Pagination to work natively. Also, your Route Parameter is redundant, and is not actually being used, so you can remove that too:

routes/web.php (or api.php, etc.)

Route::get('/albums', 'AlbumController@list');

AlbumController.php:

public function list() {
  return Album::with(['group', 'event', 'event.translation'])
  ->orderBy('id', 'desc')
  ->simplePaginate(12);
}
  • Related