You can reflash session data in the middleware before redirecting.
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?
This is a web route???
Make sure that the StartSession middleware is before your custom middleware.
Please or to participate in this conversation.