The HTTP status code 429 (Too Many Requests) indicates that the user has sent too many requests in a given amount of time. In Laravel, you can return this status code using the abort helper function with the status code as the first argument:
You can also use the response helper function to return a JSON response with the status code and message:
To handle this in a more elegant way you can use the throttle middleware which can be added to your routes or controllers. This middleware can be configured to limit the number of requests that can be made in a given amount of time.
For example, you can limit a specific route to 60 requests per minute by adding the throttle middleware to the route and setting the maximum number of requests:
In this example, the throttle middleware is limiting the /route endpoint to 60 requests per minute. If a user exceeds this limit, they will receive a 429 Too Many Requests response.
Note: you can also use the ThrottleRequests trait in your controllers to limit the number of requests on a controller-by-controller basis.
In this example, the index method of the ExampleController will be limited to 60 requests per minute.