启用访问会话时无法更改语言环境

时间:2019-07-13 20:12:55

标签: php laravel session locale middleware

这是Locale.php中间件:

<?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);
    }
}


kernel.php包括:

    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();
  }
}

问题是当我在kernel.php-> $ middleware []中启用StartSession :: class时 更改区域设置可以正常工作,但是我无法捕获Session数据,例如Session :: get('message');等

当我禁用它时,获取Session数据没有问题,但是现在我无法更改语言环境。 我如何摆脱这种麻烦?

0 个答案:

没有答案