Debug School

rakesh kumar
rakesh kumar

Posted on

how to perform rate limiting using middleware in laravel9 with example

laravel-9-rate-limiting-global-and-for-guestsusers
using-the-rate-limiter-in-laravel
laravel-and-api-rate-limiting
rate-limit-laravel-8-and-9

In Laravel, rate limiting can be implemented using middleware. Here is an example of how to create a custom middleware that limits the number of requests a user can make in a given time period:

  1. Create a new middleware class using the command php artisan make:middleware RateLimiter
  2. In the handle method of the middleware class, check the number of requests made by the user and compare it to the maximum allowed.
  3. If the number of requests is greater than the maximum allowed, return a response with a status code of 429 (Too Many Requests).
  4. If the number of requests is less than the maximum allowed, continue processing the request.
  5. In your app/Http/Kernel.php file, add the middleware to the appropriate middleware group or route.
class RateLimiter
{
    public function handle($request, Closure $next, $maxAttempts = 60, $decayMinutes = 1)
    {
        $key = $this->resolveRequestSignature($request);

        if ($this->limiter->tooManyAttempts($key, $maxAttempts, $decayMinutes)) {
            return response()->json([
                'message' => 'Too Many Requests'
            ], 429);
        }

        $this->limiter->hit($key, $decayMinutes);

        $response = $next($request);

        return $this->addHeaders(
            $response, $maxAttempts,
            $this->calculateRemainingAttempts($key, $maxAttempts)
        );
    }
}
Enter fullscreen mode Exit fullscreen mode

Image description

Image description

In your app/Http/Kernel.php file, add the middleware to the appropriate middleware group or route:

protected $routeMiddleware = [
    ...
    'throttle' => \App\Http\Middleware\RateLimiter::class,
];
Enter fullscreen mode Exit fullscreen mode

and in your routes file you can use it like this:

Route::middleware(['throttle:60,1'])->group(function () {
    Route::get('/', 'HomeController@index');
});
Enter fullscreen mode Exit fullscreen mode

Top comments (0)