更新时间:2023-12-03 22:52:46
Laravel的中间件类\Illuminate\Session\Middleware\StartSession
负责启动会话.在L5.2之前,它是在每个请求上运行的,因为它是全局中间件堆栈的一部分.现在,它是可选的,因为L5.2希望在同一应用程序中同时允许Web UI和API.
Laravel's middleware class \Illuminate\Session\Middleware\StartSession
is responsible for starting your session. Before L5.2, this ran on every request because it was part of the global middleware stack. Now, it's optional because L5.2 wants to allow for both a web UI and an API within the same application.
如果打开app/Http/Kernel.php
,您会看到StartSession
中间件是名为web
的中间件组的一部分.您需要在其中放置所有路线,以便您的示例起作用.
If you open up app/Http/Kernel.php
, you'll see that the StartSession
middleware is part of a middleware group called web
. You need to put all your routes inside there for your example to work.
Route::group(['middleware' => ['web']], function () {
Route::get('/set/{value}', function($value) {
var_dump(Session::getId());
Session::set('test', $value);
return view('welcome');
});
Route::get('/get', function() {
return 'Get ' . Session::get('test');
});
});
您可以看到web
中间件组还负责其他事情,例如在所有视图上提供$errors
变量.
You can see that the web
middleware group is also responsible for other things like providing the $errors
variable on all views.
您可以在文档中阅读有关此内容的更多信息:
You can read more about it in the docs:
默认情况下,
routes.php
文件包含单个路由以及将web
中间件组应用于其包含的所有路由的路由组.该中间件组为会话提供会话状态和CSRF保护.
By default, the
routes.php
file contains a single route as well as a route group that applies theweb
middleware group to all routes it contains. This middleware group provides session state and CSRF protection to routes.
任何未放置在web
中间件组中的路由将无权访问会话和CSRF保护,因此请确保将需要这些功能的所有路由都放置在该组中.通常,您会将大部分路线放置在该组中:
Any routes not placed within the web
middleware group will not have access to sessions and CSRF protection, so make sure any routes that need these features are placed within the group. Typically, you will place most of your routes within this group: