6

In my Laravel 5.8 app I have many API routes which return paginated results. If I make a request to my API appending the following query string I can disable pagination.

http://api.test/users/?no_paginate=1

My question is... how can I disable no_paginate from being used on certain routes? I'd preferbly want some validation to go in the request class but I can't find anything in the docs for that.

itsliamoco
  • 1,028
  • 1
  • 12
  • 28

2 Answers2

8

You can do this using a Global Middleware.

  1. Create a DisableNoPaginate Middleware:

    php artisan make:middleware DisableNoPaginate
    
  2. Then define what the middleware should do (DisableNoPaginate.php):

    <?php
    namespace App\Http\Middleware;
    
    use Closure;
    
    class DisableNoPaginate
    {
        public function handle($request, Closure $next)
        {
            //remove no_paginate param from request object
            unset($request['no_paginate']);
    
            return $next($request);
        }
    }
    
  3. Arrange for the middleware to run on all routes (routes.php):

    $app->middleware([
        App\Http\Middleware\DisableNoPaginate::class
    ]);
    

Now the no_paginate query param should be stripped from all your incoming requests.

Sapnesh Naik
  • 11,011
  • 7
  • 63
  • 98
0

For the best approach to get users either paginate or get all listing by below code in UsersController

public function index($type = null, Request $request)
{
    $builder = User::where(/*query*/);

    if($type == "paginate") {
        $items = $builder->paginate(10);
    } else {
        $items = $builder->get();
    }

    return view("users.index", ['users' => $items]);
}

Here is the route in web.php/api.php file

Route::get('/{type?}', ['as' => 'users.index', 'uses' => 'UsersController@index']);

Here url will be

http://api.test/users/paginate // get pagination response.
http://api.test/users          // get response without pagination

I think this will help you.

Lakhwinder Singh
  • 5,536
  • 5
  • 27
  • 52