I have a simple question in laravel8
I tested two codes, but I didn't find any differnces. they look like same for me. even I clicked tons of time and both gave me 'too many requests'.
Route::middleware('api')->get('/user', function (Request $request) {
return "aaa";
});
Route::get('/user', function (Request $request) {
return "aaa";
});
what is the role of 'throttle:api' and SubstitueBindings?
'api' => [
'throttle:api',
\Illuminate\Routing\Middleware\Substitu\Illuminate\Routing\Middleware\SubstituteBindings::classteBindings::class,
],
In that same file kernel.php
you will find the middlewares for the web
requests which is the default mode.
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
So web
is for statefull request, with session, cookies, csrf token, session authentification ....
And api
is for stateless request, so without those functionalities stated above but with another middleware throttle which limits number of request per minute by IP (check the config for the limit, default 60/mn).
The SubstituteBindings is common to both, it handles the binding of the parameters configured in the route declaration.
usually, you dont stack those two on top of each other. To use them, use the already present files web.php
and api.php
. how does that work ? Check the content of App\Providers\RouteServiceProvider
public function boot()
{
$this->configureRateLimiting();
$this->routes(function () {
Route::prefix('api')
->middleware('api')
->namespace($this->namespace) //the value here is \App\Http\Controllers
->group(base_path('routes/api.php'));
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
});
}
You can edit this file if your project can be seperated in more groups.
For example, I used it once to make 5 different groups, each having its own route file because I had 4 different authentifiable Entities (Admin, owner, user, audit,...) on top of the common one(web) Each having its own namespace (controller base namespace) and its own session middlewares