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

d-stephane's avatar

Validator and locale : session problem with Laravel 11

Hello,

On the website i’m developing I have a little session problem. The website is in 3 languages, so I have a menu to switch between languages. To make this work I had to add the following code in the bootstrap/app.php (lines 4, 5, 14, 15) :

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Session\Middleware\StartSession;
use App\Http\Middleware\SetLocale;

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(StartSession::class);
        $middleware->append(SetLocale::class);
    })
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })->create();

SetLocale class :

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Session;

class SetLocale
{
    public function handle(Request $request, Closure $next): Response
    {
        if ($request->session()->has('locale')) {
            App::setLocale($request->session()->get('locale'));
        }

        return $next($request);
    }
}

LanguageController class and route :

Route::get('language/{lang}', [LanguageController::class, 'switchLanguage'])->name('language');
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Log;

class LanguageController extends Controller
{
    public function switchLanguage(Request $request)
    {
        $lang = $request->lang;

        if (! in_array($lang, ['fr', 'en', 'de']))
            $lang = config('app.locale');

        session(['locale' => $lang]);

        return redirect()->back();
    }
}

All this works very well for languages, but the validation of forms only works half way. By this i mean that when i validate a form without filling in the mandatory fields, validation stops the process and return to the form page, but does not display the fields in error. If i deactivate my code added in bootstrap/app.php the validation works at 100% but not the feature for languages Any idea how to fix this little problem ?

0 likes
1 reply
d-stephane's avatar

Solution : replace

$middleware->append(StartSession::class);
$middleware->append(SetLocale::class);

by

$middleware->web([SetLocale::class]);

in bootstrap/app.php

Please or to participate in this conversation.