How to limit number of requests per IP address in Laravel 8

Laravel provides variety of custom rate limiter services out of the box which allows you to restrict the traffic to given routes. To use Laravel's rate limiter service, you need to set rate limiter.

In this article, we will discuss on how you can set number of request per IP address to specific routes. So let's start working on code.

First of all open App\Providers\RouteServiceProvider class and add configureRateLimiting method in it.

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Support\Facades\RateLimiter;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Configure the rate limiters for the application.
     *
     * @return void
     */
    protected function configureRateLimiting()
    {
        RateLimiter::for('global', function (Request $request) {
            return Limit::perMinute(10)->by($request->ip());
        });
    }
}

RateLimiter facade's for method accepts two parameters. First one defines the name of limit and second closure that returns limit configuration which will apply on route. Illuminate\Cache\RateLimiting\Limit class instance will define Limit configuration.

By default, after limit exceeds, application will return response with a 429 HTTP status code. If you want to send custom response, you can chain response method.

RateLimiter::for('ip_address', function (Request $request) {
    return Limit::perMinute(10)->by($request->ip())->response(function() {
        return response('Your return message', 429);
    });
});

After you define rate limit in AppServiceProvider, now you need to attach with routes or route group using throttle middleware. Open routes/web.php file and add groups around the routes which you want to limit.

<?php

use App\Http\Controllers\VideoController;

Route::middleware(['throttle:ip_address'])->group(function () {
    Route::get('/video-view', [VideoController::class, 'videoView']);
});

That's it now every request for these routes will limited to 10 requests per ip address.