Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

tuyendev's avatar

Why Laravel default generated code add param 'api' to ThrottleRequest Middleware

Hey there, it's been quite a while since I last dabbled in Laravel. I recently dove back into it and ran into something puzzling while checking out some sample code. Check this out:

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],
 
    'api' => [
        \Illuminate\Routing\Middleware\ThrottleRequests::class . ':api',
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],
];

Even though we've specified that the Throttle Middleware should only run within the 'api' group, I'm a bit puzzled about why we still need to add the 'api' parameter. Can anyone shed some light on this for me? Thanks a bunch, folks!

0 likes
1 reply
vincent15000's avatar

I think that it's the rate limiter name defined in the RouteServiceProvider.php file.

You can name this rate limiter as you want : api, products, ...

RateLimiter::for('api', ...

The rate limiters are defined in the boot() method in the route service provider.

public function boot(): void
{
    RateLimiter::for('api', function (Request $request) {
        return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
    });

    $this->routes(function () {
        Route::middleware('api')
            ->prefix('api')
            ->group(base_path('routes/api.php'));

        Route::middleware('web')
            ->group(base_path('routes/web.php'));
    });
}

So it could be like this.

RateLimiter::for('my_super_rate_limiter', function (Request $request) {
    return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
});

And then in the Kernel.php file it would look like this.

\Illuminate\Routing\Middleware\ThrottleRequests::class . ':my_super_rate_limiter',

Please or to participate in this conversation.