Using config to determine whether to use ThrottleRequests or ThrottleRequestsWithRedis #50930
Replies: 2 comments
-
Did you find a solution here? |
Beta Was this translation helpful? Give feedback.
-
This fails because of a timing issue in the Laravel application lifecycle. Route files (and the The configuration for the cache driver ( You were on the right track thinking about a Service Provider. This is the cleanest, most robust, and idiomatic way to handle this. It ensures your logic runs at the correct point in the application lifecycle and respects the configuration system. ->withMiddleware(function (Middleware $middleware) {
if (env('CACHE_STORE') === 'redis') {
$middleware->throttleWithRedis();
}
}) This works because However, as you suspected, this is considered bad practice in Laravel. The official documentation strongly advises against using the The main reason is configuration caching. When you run Another method that comes to my mind is creating a custom middleware. public function handle(Request $request, Closure $next, ...$parameters): Response
{
$throttleClass = config('cache.default') === 'redis'
? ThrottleRequestsWithRedis::class
: ThrottleRequests::class;
$throttleMiddleware = $this->container->make($throttleClass);
return $throttleMiddleware->handle($request, $next, ...$parameters);
} I hope I've provided some ideas; however, the provider approach is probably the best method. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
How would you go to make the
throttle
middleware dynamic based on its environment (availability of redis)?ThrottleRequests
vsThrottleRequestsWithRedis
This blows everything up:
This works, but I'm wondering if directly calling
env()
is desired...The above is Laravel 11 code, but it applies as well to older Laravel versions using a HttpKernel.
I know it could be done in a ServiceProvider's
boot()
method by revisiting and replacing the already registeredthrottle
alias, but I'm somehow tempted to try to register it early on properly...Beta Was this translation helpful? Give feedback.
All reactions