I am trying to make an api rest for the paging of a data table (daily bread when in CRUD), but I want to make it possible to put default values in the parameters that determine the current page and the number of items to return if not specified by means of the url, to give me to understand better my route is defined as follows:
Route::get('banks/{page}/{per}', 'BankController@index');
And my controller is defined like this:
public function index($page = 1,$per = 5)
{
$banks = bank::orderBy('id','DESC');
$banks = $banks->paginate($per,['*'],'page',$page);
return [
'pagination' => [
'total' => $banks->total(),
'current_page' => $banks->currentPage(),
'per_page' => $banks->perPage(),
'last_page' => $banks->lastPage(),
'from' => $banks->firstItem(),
'to' => $banks->lastItem(),
],
'banks' => $banks
];
}
I want to do that if a 'per' is not defined, 5 is taken as the default value, and if a 'page' is not defined or a 'per'se takes 1 and 5 as default values respectively
I tried to follow the Laravel documentation but it is not in my native language and I did not understand the issue of making a middleware for the default values, in the end try doing it in the following way:
Route:
Route::get('banks/{page}/{per}', 'BankController@index')->middleware('defaults');
Kernel:
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'defaults' => \Illuminate\Routing\Middleware\SetDefaultLocalForUrls::class,
];
Middleware:
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\URL;
class SetDefaultLocaleForUrls
{
public function handle($request, Closure $next)
{
URL::defaults(['page' => '1']);
URL::defaults(['per' => '5']);
return $next($request);
}
}
But nothing works for me, in postman I miss the error of
Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException
No message