How to rate limit per day in laravel?

by raphael_tillman , in category: PHP Frameworks , 4 months ago

How to rate limit per day in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by adan , 4 months ago

@raphael_tillman 

In Laravel, you can rate limit requests per day by using the built-in rate limiting features provided by Laravel's middleware. Here's how you can set up rate limiting per day in Laravel:

  1. Open the AppHttpKernel.php file in your Laravel project.
  2. Add a new rate limiting middleware and define the rate limiting rules per day. You can use the throttle middleware provided by Laravel for rate limiting. Here's an example of how you can set up rate limiting to 100 requests per day:
1
2
3
4
5
6
7
8
use IlluminateRoutingMiddlewareThrottleRequests;

protected $middlewareGroups = [
    'web' => [
        // other middleware...
        'throttle:100,1440', // 100 requests per day (60 requests per hour * 24 hours)
    ],
];


In the above code snippet, 100 is the maximum number of requests allowed and 1440 is the number of minutes in a day (60 minutes * 24 hours).

  1. You can also customize the response message and status code for rate-limited requests. You can add a middleware group for API requests if needed:
1
2
3
4
'api' => [
    'throttle:100,1440', // 100 requests per day for API requests
    'bindings',
],


  1. Save the changes and test rate limiting by making multiple requests to your application endpoint. Once the rate limit is reached, subsequent requests will receive a 429 Too Many Requests response.


By following these steps, you can easily set up rate limiting per day in your Laravel application to control the number of requests made to your endpoints.