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

uhbc's avatar
Level 1

Changing Locale Causes Problem with Session

Here is the Locale.php middleware:

<?php

namespace App\Http\Middleware;

use Closure;
use Session;
use Config;
use App;
class Locale
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
      $locale = Session::get('locale', Config::get('app.locale'));
      App::setLocale($locale);
      
      return $next($request);
    }
}


And kernel.php includes:

    protected $middleware = [
        \App\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
        \App\Http\Middleware\TrustProxies::class,
        \Illuminate\Session\Middleware\StartSession::class,  #<<<-- This causes the problem on catching Session values..
        \App\Http\Middleware\Locale::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
        ],
    ];

Web.php :

Route::get('/langs/{lang?}', 'LanguageController@setLang')->name('setLang');

LanguageController:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Session;
use App;
use Redirect;
use App\TranslatorModel;
class LanguageController extends Controller
{
  
  public function setLang($lang){
    if (!in_array($lang, [ 'en', 'ru', 'su', 'de', 'fr'])) {
      $lang = 'en';
    }
    Session::put('locale', $lang);
    return back();
  }
}

The problem is when I'm enabling the StartSession::class in kernel.php -> $middleware[ ] Changing locale works fine but I'm not being able to catch Session data, such as Session::get('message'); etc.

When I'm disabling it, there's no problem with getting Session data but now I can't change the locale. How do I get out of this trouble?

0 likes
1 reply

Please or to participate in this conversation.