Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[8.x] Adds attempt method to Rate Limiter #38313

Merged
merged 4 commits into from
Aug 10, 2021
Merged

[8.x] Adds attempt method to Rate Limiter #38313

merged 4 commits into from
Aug 10, 2021

Conversation

DarkGhostHunter
Copy link
Contributor

@DarkGhostHunter DarkGhostHunter commented Aug 10, 2021

What?

You can use the attempt() from the Rate Limiter to execute a callback if available.

use Illuminate\Support\Facades\RateLimiter;

RateLimiter::attempt('something', 5, function () {
    // ...
});

Fourth argument, decaySeconds, is default to 60.

How?

It just simply wraps the tooManyAttempts() and hit() in one call. Syntactic sugar for this:

use Illuminate\Support\Facades\RateLimiter;

if (RateLimiter::tooManyAttempts('something', 5)) {
    return false
}

// Do something...

RateLimiter::hit('something', 60);

return true;

If the shortcut fails, false is returned. Otherwise, it returns result of the callback, or true if the result is null. THis allows the developer to programmatically proceed if the call wasn't executed.

use Illuminate\Support\Facades\RateLimiter;

$executed = RateLimiter::attempt('something', 5, fn() => 'foo', 60 * 60);

if ($executed) {
    return "It returned $executed";
}

Why?

  • Simplifies effective Rate Limiter usage into one method easy to understand. (Should be documented too!)

@DarkGhostHunter DarkGhostHunter changed the title Adds an attempt method w/tests. [8-x] Adds attempt method to Rate Limiter Aug 10, 2021
@driesvints driesvints changed the title [8-x] Adds attempt method to Rate Limiter [8.x] Adds attempt method to Rate Limiter Aug 10, 2021
@taylorotwell taylorotwell merged commit 6cc8aaf into laravel:8.x Aug 10, 2021
@DarkGhostHunter
Copy link
Contributor Author

Success!

@DarkGhostHunter DarkGhostHunter deleted the feat/rate_limiter_attempt branch August 13, 2021 21:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants