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.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

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

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay