Laravel: Throttling any method class elegantly

You only need one magic method

Italo Baeza Cabrera
2 min readJun 4, 2020

One of the thing the new Rate Limiter will introduce in Laravel 8 is the brain-dead easy way to throttle certain routes. It’s not documented at time of writing, but I fully expect it will be what developers need to throttle anything before hitting the controller logic without hacking their way in.

While this will become very handy for almost everybody, sometimes you won’t want to throttle the whole request, but rather, a single piece of it.

If you want to throttle a piece of code, you must use the Rate Limiter manually. Then, something that was just one line of code becomes four.

if (! $limiter->hasTooManyAttempts('doSomething', 3)) {
$class->doSomething();
$limiter->hit('doSomething', 60);
}

Instead of this doing this, I decided to create a very handy throttler for a class that could wrap this logic in one line.

Throttling a class method? What magic is this?

Yes, you can. For this, we can use a very simple concept of wrapping the object into another that will check the throttling, and call the method of the target object if it’s not throttled.

You can perfectly do something like throttling the next object method to call this way:

$class->throttle()->doSomething();

For this to work, we can create a method on a trait that will create an object that uses the Rate Limiter, checks the method to throttle, and then executes the method if the limit has not been set.

First, we will make a convenient trait we can add to any object we want.

What is that Throttler class? Well, it’s just a simple class that encapsulates the object we are using. It will pass any method to it underlying target after checking the rate limiting.

The magic happens in the _call() method. We will simply check for the class name and method name combination, and check for the attempts number. If the it’s permitted, the method will be executed, otherwise it won’t. In both cases, we return the target object.

With this, we can call the throttler, check automatically if we have called the same method too many times, and if not, call it for real. We can even chain methods with this throttle:

$object->throttle()->doSomething()->somethingElse();

Of course you can expand on this, like using a custom key, and allow to clear the throttle key or reset it’s condition, and finally, use a Closure to execute alternate logic if the action is throttled.

You can find this trait and other helpers in my Laratraits package. Give it a chance if you find something useful to use in your project.

--

--

Italo Baeza Cabrera

Graphic Designer graduate. Full Stack Web Developer. Retired Tech & Gaming Editor. https://italobc.com