Skip to main content

Command Palette

Search for a command to run...

How to Use Rate Limiter in Laravel: A Quick Guide

Updated
How to Use Rate Limiter in Laravel: A Quick Guide

Rate limiting is a crucial feature in web applications to control the number of requests a user can make to the server within a specific timeframe. This helps protect your application from abuse, such as brute force attacks and ensures fair usage of your resources. Read this if you need more information.

In this post, we'll dive deep into Laravel's rate-limiting capabilities and how to implement them in your application.

Using middleware

//routes/web/php
Route::get('/hello', function () {
    return response()
        ->json([
            'version' => '1.0.0',
            'latest_update' => '2022-01-01',
            'data' => 'Hello World!'
        ]);
})->middleware(['throttle:hello']);

Define Rate Limits in the AppServiceProvider.php


// app/providers/AppServiceProvider.php
/**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        RateLimiter::for('hello', function ($request) {
            return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
        });
    }

How it works?

Manually Incrementing Attempts

Check it out from the Laravel 11 resource from here.

Route::get('/create-transcript', function (Request $request) {
    if (RateLimiter::tooManyAttempts(
        key: 'transcript:' . $request->ip(),
        maxAttempts: 5
    )) {
        return 'Too many attempts';
    }

    echo 'Transcript created';
    RateLimiter::increment('transcript:' . $request->ip(), amount: 5);
});

More from this blog

M

Makeinfo Blog | Tech Guides, SEO Tips, and Marketing Automation

127 posts

Blogging helpful tech tips, how-to tutorials since 2020