Source: bannister.me

Custom Throttle Middleware

Category: Laravel, Laravel

James Bannister • July 24, 2019 • 4 minute read For example, the below snippet in a routes file would restrict the number of requests a user or IP address could make to 60 per minute: Since Laravel 5.6, we've even be able to do dynamic rate limiting, based on an attribute of the User model; representing a column in your users table - the below example demonstrates a column called rate_limit dictating the number of requests a user can make per hour: You could set this to 3,600 by default, and then bump this up or down for particular users as their needs dictate.

This is actually quite easy to implement once you know how - we just need to understand a little about how the existing ThrottleRequests middleware works. If you open the ThrottleRequests middleware and check out the handle() method, we can see the following: The first line of the method is what we're interested in: This is where the ThrottleRequests middleware figures out the key that it should use to track your requests.

To achieve this, we just figured out what type of IoT device we were working with and then resolved the token as appropriate from there: This then allows you to use your new middleware like so (replacing the 1 and 5 to suit your needs): Using the above approach, we were able to throttle requests using a unique route parameter, present in each of the requests, along with a unique identifier that each device was including in their payload for the request.
Newsletter

Get the latest Laravel/PHP jobs, events and curated articles straight to your inbox, once a week

Fathom Analytics | Fast, simple and privacy-focused website analytics. Fathom Analytics | Fast, simple and privacy-focused website analytics.
Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future. Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future.
Community Partners