Help us understand the problem. What is going on with this article?

Lumen 6.2 でセッションを使う

Lumen 6.2 には illuminate/session が含まれていますが、デフォルトで無効になっているので有効化させたときの手順メモ

動作環境

Windows10 Home Edition
XAMPP 7.2.17

$ php --version
PHP 7.2.17 (cli) (built: Apr  2 2019 20:11:25) ( ZTS MSVC15 (Visual C++ 2017) x64 )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies
    with Zend OPcache v7.2.17, Copyright (c) 1999-2018, by Zend Technologies
    with Xdebug v2.6.1, Copyright (c) 2002-2018, by Derick Rethans

$ php artisan --version
Laravel Framework Lumen (6.2.0) (Laravel Components ^6.0)

設定

セッション関連クラスの登録

bootstrap/app.php に下記を追加

bootstrap/app.php
$app->singleton(Illuminate\Session\SessionManager::class, function () use ($app) {
    return $app->loadComponent('session', Illuminate\Session\SessionServiceProvider::class, 'session');
});

$app->singleton('session.store', function () use ($app) {
    return $app->loadComponent('session', Illuminate\Session\SessionServiceProvider::class, 'session.store');
});


$app->middleware([
     \Illuminate\Session\Middleware\StartSession::class,
]);

config/session.php の追加

プロジェクトのルートに config フォルダを作成。その中に session.php を配置

session.php の内容は Laravelconfig/session.php と同じ

laravel/session.php at master - laravel/laravel

セッションの保存フォルダの作成

storage/framework の下に sessions フォルダを作成する

$ mkdir storage\framework\sessions

動作確認

テストコード

routes/web.php
// Test Session
$router->get('/test', function (\Illuminate\Http\Request $request) {

    $counter = $request->session()->get('counter') ?: 0;
    $request->session()->put('counter', ++$counter);

    return response()->json([
        'session.counter' => $request->session()->get('counter')
    ]);
});

テストサーバー起動

$ php -S localhost:8000 -t public

アクセス

WEBブラウザで http://localhost:8000/test を開くと以下のように表示される

{"session.counter":1}

セッションが正常に機能していれば、リロードする度に数値が 1 づつ増えていく

参考

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away