8
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

LaravelでSessionをコンストラクタで使うときの注意点

Last updated at Posted at 2019-01-11

LaravelでSessionに何かを入れておく処理を書いて、一度アクセス(セッションに保存)しておき、、

class LoginUserController extends Controller
{
    public function index(Request $request)
    {
            $token = 'hoge';
            // セッションIDの発行
            session()->regenerate();
            // セッションへデータを保存する
            session(['token' => $token]);
           
            $token = session('accessToken'); // セッションからデータを取り出す
            Log::debug($token); // ちゃんと表示される
        }
}

別のControllerのコンストラクタで(以後のアクセスの際に)Sessionから値を取り出そうとすると、あるはずの値がない。

class HogeController extends Controller
{
    public function __construct()
    {
        $token = session('accessToken');
        Log::debug($token);
    }

    public function index()
    {
        // 
    }
}

logは空文字。


対処法

Kernel.phpの以下を変更すると治る。

app/Http/Kernel.php

class Kernel extends HttpKernel
{
    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,                   // ここを追加
    ];

    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',
        ],
    ];
}

8
7
2

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
8
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?