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:
- Create a new middleware class using the command php artisan make:middleware RateLimiter
- In the handle method of the middleware class, check the number of requests made by the user and compare it to the maximum allowed.
- If the number of requests is greater than the maximum allowed, return a response with a status code of 429 (Too Many Requests).
- If the number of requests is less than the maximum allowed, continue processing the request.
- 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)
);
}
}
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,
];
and in your routes file you can use it like this:
Route::middleware(['throttle:60,1'])->group(function () {
Route::get('/', 'HomeController@index');
});
Latest comments (0)