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

night_driver's avatar

Session data not saved with redirection

Hello,

I try to set a data in the session but when i use redirect it seems it's not saved. In my middleware it's always empty.

When I tried to return a view in the controller and seems to works.

I use database for the session driver. Here my code

Thank you very much !!

Controller

    /**
     * @param SetLanguageRequest $request
     * @return mixed
     */
    public function setLanguage(SetLanguageRequest $request): mixed
    {

        $requestValidated = $request->validated();

        Session::put('locale', $requestValidated['locale']); //es or en

        App::setLocale($requestValidated['locale']);

        return redirect()->back();
    }

Middleware

class SetLanguage
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        if(Session::has('locale')) {
            App::setLocale(Session::get('locale'));
        }

        return $next($request);
    }
}

app.php

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->append(SetLanguage::class);
    })
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })->create();

.env

SESSION_DRIVER=database
SESSION_LIFETIME=120
SESSION_ENCRYPT=false
SESSION_PATH=/
SESSION_DOMAIN=null
0 likes
3 replies
night_driver's avatar
night_driver
OP
Best Answer
Level 1

Solution found ! I post the solution if someone needs.

Without adding the middleware to the group "web". It will not have access to sessions meaning it will always be empty.

instead of

app.php

$middleware->append(SetLanguage::class);

do

app.php

$middleware->appendToGroup('web', SetLanguage::class);

Please or to participate in this conversation.