Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here

Rate Limit: Maximum Requests per Minute

Premium
2:33

Let's talk about a feature called Rate Limiting, or in other words, called Throttling. What happens if the API is called too many times per minute or hour? Then the user receives an error with the message Too Many Attempts. and 429 Too Many Requests HTTP status.


First, we must enable the API throttling for the Middleware.

bootstrap/app.php:

return Application::configure(basePath: dirname(__DIR__))
->withProviders()
->withRouting(
web: __DIR__.'/../routes/web.php',
api: __DIR__.'/../routes/api.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
apiPrefix: 'api/v1',
)
->withMiddleware(function (Middleware $middleware) {
$middleware
->statefulApi()
->withThrottledApi();
})
->withExceptions(function (Exceptions $exceptions) {
//
})->create();

Next, we can configure the rate limiter in the AppServiceProvider boot method. For example, we can limit the whole API to six requests per minute.

app/Providers/AppServiceProvider.php:

use Illuminate\Http\Request;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Support\Facades\RateLimiter;
 
class AppServiceProvider extends ServiceProvider
{
// ...
 
public function boot(): void
{
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(6)->by($request->user()?->id ?: $request->ip());
});
}
}

If you need to set different rate limiters on some routes, this can be done using...

The Full Lesson is Only for Premium Members

Want to access all of our courses? (31 h 16 min)

You also get:

55 courses
Premium tutorials
Access to repositories
Private Discord
Get Premium for $129/year or $29/month

Already a member? Login here

Comments & Discussion

M
M ✓ Link copied!

to set the json message.

    public function boot(): void
    {
        RateLimiter::for('api', function (Request $request) {

            if ($request->user()?->role === 'admin') {
                return Limit::none();
            }

            // return Limit::perMinute(2)->by($request->user()?->id ?: $request->ip());

            return Limit::perMinute(2)
            ->by($request->user()?->id ?: $request->ip())
            ->response(function (Request $request, array $headers) {
                if ($request->expectsJson()) {
                    return response()->json([
                        'message' => 'You have hit a rate limit. try again after some time.'
                    ], 429);
                }
                return response('You have hit a rate limit. try again after some time.', 429, $headers);
            });
        });
    }