Laravel Advanced Auth & Jobs · 8 min read

Laravel Rate Limiting

Lesson 19 of 33 in the Laravel learning path.

How do I throttle a login or search endpoint?

Rate limiting caps how often a client can hit a route. Login needs a custom key, because the person is not authenticated yet and one address should not get unlimited guesses by rotating emails. RateLimiter::for registers that key, and middleware('throttle:login') applies it. Five attempts per minute are allowed for an email and IP together, and twenty per minute for the IP alone.

Search uses the built-in throttle middleware with a number and a decay: throttle:30,1 allows 30 requests in one minute. Laravel keys that limiter by the signed-in user id when there is one, otherwise by IP. The 31st search, or the attempt past either login cap, returns HTTP 429 with a Retry-After header.

Syntax & Parameters

Syntax
RateLimiter::for('login', function (Request $request) {
    return Limit::perMinute(5)->by($request->ip());
});
Route::post('/login', [LoginController::class, 'store'])->middleware('throttle:login');
Route::get('/lessons', [LessonController::class, 'index'])->middleware('throttle:30,1');

Example

routes/web.php
<?php

use App\Models\Lesson;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;

RateLimiter::for('login', function (Request $request): array {
    $email = $request->input('email');
    $email = is_string($email) ? Str::lower($email) : '';

    return [
        Limit::perMinute(5)->by('email|'.$email.'|'.$request->ip()),
        Limit::perMinute(20)->by('ip|'.$request->ip()),
    ];
});

Route::post('/login', function (Request $request) {
    $credentials = $request->validate([
        'email' => ['required', 'email'],
        'password' => ['required', 'string'],
    ]);

    if (! Auth::attempt($credentials)) {
        throw ValidationException::withMessages([
            'email' => 'Those credentials do not match our records.',
        ]);
    }

    $request->session()->regenerate();

    return redirect()->intended('/lessons');
})->middleware('throttle:login')->name('login.store');

Route::get('/lessons', function (Request $request) {
    $term = $request->input('q', '');
    $term = is_string($term) ? $term : '';

    $lessons = Lesson::query()
        ->when($term !== '', function ($query) use ($term) {
            $query->where('title', 'like', '%'.$term.'%');
        })
        ->orderBy('title')
        ->paginate(10)
        ->withQueryString();

    return response()->json([
        'data' => $lessons->getCollection()->map(fn (Lesson $lesson) => [
            'id' => $lesson->id,
            'title' => $lesson->title,
            'track' => $lesson->track,
        ])->values(),
        'current_page' => $lessons->currentPage(),
    ]);
})->middleware('throttle:30,1')->name('lessons.index');

Expected Output

POST /login with the same email and IP, wrong password, 5 times
The fifth attempt is still inside the email cap.

POST /login a 6th time in that minute
HTTP 429
Retry-After: 60
Body: Too Many Attempts.

GET /lessons?q=algebra 30 times in one minute from one IP
HTTP 200

GET /lessons?q=algebra the 31st time in that minute
HTTP 429

Line-by-Line Walkthrough

  1. RateLimiter::for('login') registers a named limiter. throttle:login on the route looks that name up when the request arrives.
  2. The email is read only when it is a string, then lowercased, so the same address cannot dodge the cap by changing letter case.
  3. The first Limit allows 5 requests a minute for that email paired with the client IP. A wrong password still consumes one of the five.
  4. The second Limit allows 20 requests a minute for the IP alone, so rotating emails from one address still hits a ceiling.
  5. The login route validates the body, calls Auth::attempt, and regenerates the session after success. The throttle middleware runs before that closure.
  6. A failure throws ValidationException, which Laravel renders as 422. Those failures count toward the limiter because the middleware already ran.
  7. Search uses middleware('throttle:30,1'): 30 requests, decay of 1 minute. This numeric form does not need RateLimiter::for.
  8. The numeric limiter keys by the authenticated user id, or by IP when nobody is signed in, and it includes the route in the key.
  9. Past either login limit, or past 30 searches in the minute, Laravel responds with 429 and a Retry-After header. A service provider boot method is the usual home for RateLimiter::for when several route files share the name.

Common Pitfalls & Security

A limiter that is not attached to the route does not run. Defining RateLimiter::for('login') and then forgetting middleware('throttle:login') leaves the password endpoint open. The numeric form throttle:30,1 is a different limiter from the named one, and mixing up the decay minutes changes the window.

  • throttle:5,1 means five attempts per one minute. Reading the second number as seconds makes the cap far tighter than you wrote.
  • Keying login only by IP locks a whole classroom that shares one address. Pair the email with the IP, and keep a separate IP ceiling.
  • Keying login only by email lets many addresses from one host try forever. The per-IP Limit is what stops that sweep.
  • Auth middleware is not a rate limit. It checks who the user is. Login has no user yet, so the limiter has to key off the request itself.
  • The framework cache stores the counters. The array cache does not survive the next PHP process, so a limiter appears to work in one test and reset on the next request.
  • Returning every Lesson attribute from a search response is a separate leak. The route maps id, title, and track so the throttle example does not publish the whole row.

Best Practices & Modern Standards

Name a limiter when the key is part of the rule, and attach it with the throttle middleware. Login gets a short per-email budget and a wider per-IP budget. Search can use throttle:30,1 when the default user-or-IP key is enough. Keep the registration and the route together so a reader can see both, and move RateLimiter::for to AppServiceProvider::boot when API routes need the same name.

Return 429 when the cap is spent, and let Retry-After tell a well behaved client when to call again. Do not build a second counter by hand in the controller. Validate the login body after the middleware so bad passwords still count, and regenerate the session only after Auth::attempt succeeds.

Real-World Use

Someone posts Ada's email and a long list of passwords to /login. After five tries in a minute from that IP, the named limiter returns 429 and the account is not checked again until the window passes. A noisy catalog search is capped at 30 requests a minute, so one client cannot page the lesson list as fast as the database will answer.

Frequently Asked Questions

What does throttle:login call?

The limiter registered with RateLimiter::for('login'). The route middleware looks up that name and applies the Limit objects it returns.

What does throttle:30,1 mean?

Thirty requests per one minute. The first number is the maximum and the second is the decay in minutes. This form does not use a named RateLimiter.

Which response does a client get after the cap?

HTTP 429, with a Retry-After header. Laravel sends that response from the throttle middleware before the route closure runs.

Why is the login key the email and the IP?

The email cap slows guesses against one account from one address. The separate IP cap slows a client that tries many emails. There is no signed-in user id to use yet.

Need more coins?

You do not have enough coins for this action.

Your balance: 0 coins

Share

Reactions

Loading reactions…