php 36 lines · 7 steps

Defining rate limiters in Laravel

How a RouteServiceProvider registers named rate limiters that adapt to the authenticated user.

Explained by highlit
1<?php
2 
3namespace App\Providers;
4 
5use Illuminate\Cache\RateLimiting\Limit;
6use Illuminate\Http\Request;
7use Illuminate\Support\Facades\RateLimiter;
8use Illuminate\Support\ServiceProvider;
9 
10class RouteServiceProvider extends ServiceProvider
11{
12 public function boot(): void
13 {
14 RateLimiter::for('api', function (Request $request) {
15 return $request->user()
16 ? Limit::perMinute(120)->by($request->user()->id)
17 : Limit::perMinute(30)->by($request->ip());
18 });
19 
20 RateLimiter::for('uploads', function (Request $request) {
21 $user = $request->user();
22 
23 if ($user?->onPremiumPlan()) {
24 return Limit::none();
25 }
26 
27 return Limit::perMinute(10)
28 ->by($user?->id ?: $request->ip())
29 ->response(function (Request $request, array $headers) {
30 return response()->json([
31 'message' => 'Upload limit reached. Try again shortly.',
32 ], 429, $headers);
33 });
34 });
35 }
36}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Named rate limiters let you attach different throttling rules to routes by name instead of hardcoding limits.
  2. 2Keying limits by user id versus IP lets you give authenticated clients a higher, per-account quota.
  3. 3Returning Limit::none() or a custom response tailors throttling to plans and gives clients a clear rejection message.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Defining rate limiters in Laravel — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code