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

kvalbot's avatar

Change request's requestUri in middleware

My goal is to add a locale to the beginning of the url and redirect to the correct url. Example:

User opens domain.com/products, they should be redirected to domain.com/en/products

What I have so far:

SetLocaleMiddleware.php

    public function handle(Request $request, Closure $next)
    {
        $locale = $request->segment(1);
        if (!in_array($locale, Config::get('app.available_locales'))) {
            $locale = $this->getFallbackLocale();
            $request->headers->set('X_REWRITE_URL', '/' . $locale . '/' . $this->getRedirectPath($request));
        }

        app()->setLocale($locale);
        return $next($request);
    }

    private function getRedirectPath(Request $request): string
    {
        return $request->path() . ($request->getQueryString() ? '?' . $request->getQueryString() : '');
    }

However, if I open /products, I don't get redirected to /en/products. While debugging I found out that the requestUri property of the $request object is set earlier before the middleware is executed.

If I try to do a simple redirect($locale . '/' . $request->getRedirectPath())I lose all session info that I have. For example everything I put in the session with Session::flash() is lost, because I am basically doing a double redirect.

Is there any way to achieve what I want?

0 likes
4 replies
kvalbot's avatar

@tykus If I use $request->session()->reflash(); before redirect, I get Session store not set on request.

tykus's avatar
tykus
Best Answer
Level 104

This is a web route???

Make sure that the StartSession middleware is before your custom middleware.

kvalbot's avatar

@tykus that was it, I registered my custom middleware before the StartSession one. Thanks a lot!

Please or to participate in this conversation.