Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Ayzerobug's avatar

request() helper not working properly when Laravel is optimized

Laravel request() helper won't work when app is optimized.

public function resolveAuthMiddleware() { return strtolower(request()->header('Request-From')) == "portal" ? "auth:sanctum" : "api.auth"; }

I have a logic to check which middleware to use depending on a header Request-From value. This works perfectly when the app is not optimized. But when i run php artisan optimize, the ternary operator returns false giving me api:auth. Again when i run php artisan optimize:clear i have auth:sanctum.

PS: The request header was available when checked with telescope

0 likes
2 replies
Talinon's avatar

@ayzerobug I suspect that code you provided is within a service provider? When you optimize, behind the scenes the framework will cache your routes. This code would evaluate when you run the command, then cache the result. This is why upon every request it is returning the same value.

If you move the request() logic into its own middleware, it should then evaluate at runtime. The new middleware could invoke whatever else you need to have executed based upon the condition.

Opposed to this strategy, you may want to consider restructuring your app so the routes are segregated, and then you can assign middleware to the specific route implementations.

Snapey's avatar

Alternatively, you may be using .env values outside of config files.

Please or to participate in this conversation.