Rate limter problem when created in AppServiceProvider
when i created the rate limiter in AppServiceProvider class as the docs says i lost the access to the RateLimter class method like AvalibleIn() , Attempts(), etc , what i want is that i redrict with a message to user that till him when he can try
note: this RateLimiter::availableIn('user-updates' in here gets 0
RateLimiter::for('user-updates', function (Request $request) {
return Limit::perMinutes(2, 4)->by('user-updates')->response(function () use ($request) {
return redirect()
->route('user.update', ['username' => $request->username])
->withErrors(['email' => 'you have exceeded the limit for this update request please try again after '. RateLimiter::availableIn('user-updates') . ' seconds']);
});
});
In AppServiceProvider you define your rate limiter by setting name and rules. This defines rate limiter which allows 10 requests per minute per IP address:
protected function boot(): void
{
RateLimiter::for('my-rate-limiter', function (Request $request) {
return Limit::perMinute(10)->by($request->ip());
});
}
In routes/web.php (or api.php) you attach your defined rate limiter to routes using it's name in throttle middleware:
@Glukinho I have changed the strategy. I created a dedicated middleware called RateLimiter, which is responsible for checking and setting the rate limit on controller actions. The middleware returns true if the maximum number of attempts has been reached, and false otherwise. In the controller, I can redirect back with errors if the rate limit has been exceeded.
@minaremonshaker this is acceptable too. However, Laravel has all this by itself, no need to reinvent the same, just use what is suggested by a framework.
@Glukinho The Laravel Rate Limiter that we set up in the AppServiceProvider doesn’t fully support the feature I need. As shown above, I want to return the remaining decay seconds or minutes to the user, but this isn’t working as expected. That’s why I created a custom solution using middleware instead