はじめに
Laravelではユーザーのセッションはファイルに保持しています
ファイルが出力される場所は「storage/sessions」となります
ここでは、セッションの保存方法にデータベースを使用する方法についてまとめました
環境
PHP 7.3
Laravel Framework 6.13.1
セッションをデータベースに保存する流れ
1. セッションを保持するテーブルを作成します
以下のコマンドを実行して、マイグレーションファイルを作成します
$ php artisan session:table
コマンドを実行すると、以下のマイグレーションファイルが作成されます
database/migrations/YYYY_MM_DD_hhmmss_create_sessions_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateSessionsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('sessions', function (Blueprint $table) {
$table->string('id')->unique();
$table->unsignedBigInteger('user_id')->nullable();
$table->string('ip_address', 45)->nullable();
$table->text('user_agent')->nullable();
$table->text('payload');
$table->integer('last_activity');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('sessions');
}
}
マイグレーションコマンドを実行して、セッションテーブルを作成します
$ php artisan migrate
2. セッションの保持方法をファイルからデータベースに変更します
.envファイルのセッションドライバーをfileからdatabaseに変更します
SESSION_DRIVER=database
session.phpの設定もfileからdatabaseに変更します
config/session.php
'driver' => env('SESSION_DRIVER', 'database'),
3. キャッシュをクリアします
以下のコマンドを実行してキャッシュをクリアします
$ php artisan config:clear
まとめ
セッションの保存方法をデータベースにしてみようと思う人は参考にしてみてください