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.

👋 One new thing before you go

If you don't invest in your dev career who will?

We have created a membership program that helps cap your costs so you can build and experiment for less. And we currently have early-bird pricing which makes it an even better value! 🐥

Just one of many great perks of being part of the network ❤️

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay