Edit: Ali Ismaeel provided a great answer to my structure, but I had done a poor job of asking the question and re-wrote it. My edit history shows what he was addressing. Sorry, I'm trying to get better at asking good questions.
I have some custom middleware set up that sets the localization based on some priorities. The middleware works as expected, but because it is Middleware, it continues to run. Now normally if something executes multiple times and I only need it once, I would set a flag as a variable or session and just check its status. I can't seem to replicate this behavior with Middleware, and I believe it's because I do not know where to put it.
class Localization {
public function handle(Request $request, Closure $next): Response {
# Set Already Run Flag
if ($request->has('hasRun')) {
# Return Before Code Runs
return $next($request);
}
# Run Code
# Then Set Variable
$request->attributes->set('hasRun', true);
return $next($request);
}
}
Thank you!
It is normal that the middleware runs every time a request made on the related route. so if the middleware is applied on a group of routes , it will be applied every single time a request made on any of these routes, it is the normal behavior.
So , the middleware will run always when a request made on any related route, and the middleware responsibility is to make changes on the request if it is required or let the request proceed to its next step.
A better design of the middleware is to contain only one
return $next($request);
at the end, and any required changes can be done before it.I rewrite your code to illustrate what I mean.