- 配置文件 config/session.php
大多数是用file驱动,将session保存在storage/framework/sessions,可以考虑使用redis或者memcached 驱动实现更出色的性能
- 使用database作为驱动
需要创建数据表
php artisan session:tablephp artisan migrate
数据表内容
Schema::create('sessions', function ($table) { ???$table->string('id')->unique(); ???$table->integer('user_id')->nullable(); ???$table->string('ip_address', 45)->nullable(); ???$table->text('user_agent')->nullable(); ???$table->text('payload'); ???$table->integer('last_activity');});
- 使用session
laravel 中处理 Session 数据有两种主要方法:
全局辅助函数 session 和通过一个 Request 实例。
???public function show(Request $request, $id) ???{ ???????$value = $request->session()->get('key'); ???????// ???}
Route::get('home', function () { ???// 获取 Session 中的一条数据... ???$value = session('key'); ???// 指定一个默认值... ???$value = session('key', 'default'); ???// 在 Session 中存储一条数据... ???session(['key' => 'value']);});
通过 HTTP 请求实例操作 Session 与使用全局辅助函数 session 两者之间并没有实质上的区别
获取所有 Session 数据
$data = $request->session()->all();
要确定 Session 中是否存在某个值,可以使用 has 方法。如果该值存在且不为 null,那么 has 方法会返回 true:
if ($request->session()->has('users')) {//}
要确定 Session 中是否存在某个值,即使其值为 null,也可以使用 exists 方法。如果值存在,则 exists 方法返回 true:
if ($request->session()->exists('users')) {//}