DEV Community

Ali A. Dhillon
Ali A. Dhillon

Posted on

5 3

New simple way of creating custom Rate Limiters in Laravel 8

In Laravel we use throttle middleware to restrict the amount of traffic for a given route or group of routes. The throttle middleware accepts two parameters that determine the maximum number of requests that can be made in a given number of minutes.
For example:

Route::middleware('throttle:60,1')->get('/user', function () {
        //
});
Enter fullscreen mode Exit fullscreen mode

Here 60 is number of requests you can make in 1 minute.

Now in Laravel 8 there is a new way to create custom Rate Limiters.
We can define our custom Rate Limiter in any Service Provider typically it should be in RouteServiceProvider like so.

Rate limiters are defined using the RateLimiter facade's for method. The for method accepts a rate limiter name and a Closure that returns the limit configuration that should apply to routes that are assigned this rate limiter:

use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Support\Facades\RateLimiter;

RateLimiter::for('testing', function (Request $request) {
    return Limit::perMinute(1000);
});
Enter fullscreen mode Exit fullscreen mode

Now we can attach testing Rate Limiter using it's name with throttle middleware like throttle:testing instead of throttle:60,1:

Route::middleware('throttle:testing')->get('/user', function(){
    //
});
Enter fullscreen mode Exit fullscreen mode

For further reading check out the Laravel 8 Docs Rate Limiting.

Heroku

Deploy with ease. Manage efficiently. Scale faster.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay