LoginSignup
9
8

More than 5 years have passed since last update.

laravel5でミドルウェアでセッション使えなくて困った そんな時

Last updated at Posted at 2015-09-09

前置き

Laravelで他言語サイトを作るにあたり、ドメインの後に「/en/」「/ja/」を付けてURLを生成したい
いわゆるプレフィックスというものである。

試みたこと

先人の知恵を借りて実装
https://laracasts.com/discuss/channels/tips/example-on-how-to-use-multiple-locales-in-your-laravel-5-website/?page=1

この実装に加えて、万が一プレフィックス無しでアクセスがあった時にデフォルト言語ではなく、それまでにアクセスしていたURLからプレフィックスを判定してプレフィックスを付与したURLにリダイレクトをする設定を試みる。
新しく作成したLanguage.phpのhandle()に手を加える

public function handle($request, Closure $next)
{
    $locale = $request->segment(1);

    if ( ! array_key_exists($locale, $this->app->config->get('app.locales'))) {
        if (Session::has('locale')) {
            $this->app->setLocale(Session::get('locale'));
            return $this->redirector->to(Session::get('locale') . "/" . $request->path());
        }
        $segments = $request->segments();
        $segments[0] = $this->app->config->get('app.fallback_locale');
        Session::put('locale', $segments[0]);
        $this->app->setLocale($segments[0]);
        return $this->redirector->to($segments[0] . "/" . $request->path());
    }

    $this->app->setLocale($locale);
    Session::put('locale', $locale);

    return $next($request);
}

見事にセッションが動かない

試行錯誤

とりあえず実装を確認する

こういう時は、何度も記述した内容を振り返る
しかしこれといっておかしい箇所が見当たらない

先人の知恵を振り返る

とある記述が目に留まる

Now make that middleware run on all requests by adding it to the $middleware property in app/Http/Kernel.php. It is recommended to add it to the top of the array.

protected $middleware = [
    'App\Http\Middleware\Language',
    'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
    'Illuminate\Cookie\Middleware\EncryptCookies',
    'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
    'Illuminate\Session\Middleware\StartSession',
    'Illuminate\View\Middleware\ShareErrorsFromSession',
    'Illuminate\Foundation\Http\Middleware\VerifyCsrfToken',
];

ひょっとしたら読み込み順を変えればいけるのでは

protected $middleware = [
    'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
    'Illuminate\Cookie\Middleware\EncryptCookies',
    'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
    'Illuminate\Session\Middleware\StartSession',
    'Illuminate\View\Middleware\ShareErrorsFromSession',
    'App\Http\Middleware\Language',
    'Illuminate\Foundation\Http\Middleware\VerifyCsrfToken',
];

これでセッションが動くようになる
ただ、

「It is recommended to add it to the top of the array.」

がきになるところ

9
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
8