Laravel 会话管理:数据库驱动配置 3 个改进

问题

在 Laravel 中,支持使用数据库存储会话数据么,如果支持,该怎么做?

(提示:数据库存储会话需谨慎,大型 Web 项目请尽量使用 Redis、Memcached 等专业的缓存驱动进行存储,避免使用文件存储和数据库存储)

回答

在 Laravel 中,如果要使用数据库来存储会话数据,你需要先创建一张包含各项会话数据的表。以下是使用 Schema 建表的例子:

Schema::create('sessions', function ($table) {
    $table->string('id')->unique();
    $table->unsignedInteger('user_id')->nullable();
    $table->string('ip_address', 45)->nullable();
    $table->text('user_agent')->nullable();
    $table->text('payload');
    $table->integer('last_activity');
});

我们可以使用 Artisan 命令 session:table 来生成此迁移:

$ php artisan session:table

$ php artisan migrate

然后,修改会话配置文件(位于 config/session.php 文件中):

<?php

use Illuminate\Support\Str;

return [

    /*
    |--------------------------------------------------------------------------
    | Default Session Driver
    |--------------------------------------------------------------------------
    |
    | This option controls the default session "driver" that will be used on
    | requests. By default, we will use the lightweight native driver but
    | you may specify any of the other wonderful drivers provided here.
    |
    | Supported: "file", "cookie", "database", "apc",
    |            "memcached", "redis", "dynamodb", "array"
    |
    */

    'driver' => env('SESSION_DRIVER', 'file'),

    // 省略
];

可以看到,会话的默认驱动为 file,我们把它改成 database

    'driver' => env('SESSION_DRIVER', 'database'),

这样,我们就完成了使用数据库存储会话数据的配置工作了。

参考

本文为 Wiki 文章,邀您参与纠错、纰漏和优化
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!