Laravel 会话管理:数据库驱动配置
问题
在 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'),
这样,我们就完成了使用数据库存储会话数据的配置工作了。