5
4

More than 3 years have passed since last update.

Laravel 6系でセッションをファイルからデータベースの保存に変更する方法

Last updated at Posted at 2020-03-12

はじめに

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

まとめ

セッションの保存方法をデータベースにしてみようと思う人は参考にしてみてください

参考

HTTPセッション 6.x Laravel

5
4
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
5
4