在Laravel中的自定义中间件中使用会话 [英] Using session in custom middleware in laravel
问题描述
我有一个简单的中间件,可以检查用户会话中是否存在密钥.
I've simple middleware which checks if there is a key in user session.
<?php
namespace App\Http\Middleware;
use Closure;
class CustomAuth
{
public function handle($request, Closure $next)
{
if($request->session()->has('uid')){
return $next($request);
}
else{
return view('unauth');
}
}
}
问题是我总是收到未按要求设置会话存储".错误.这是我的路线:
The problem is that I always get "Session store not set on request." error. Here is my route:
Route::get('home', function () {
return view('home');
})->middleware('web', 'CustomAuth');
我已经在变量$ middleware中的app \ Http \ Kernel.php中添加了中间件
I've added the middleware in app\Http\Kernel.php in the variable $middleware
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\App\Http\Middleware\CustomAuth::class
];
我还尝试将路线更改为此:
I also tried changing my route to this:
Route::group(['middleware' => ['web']], function () {
Route::get('home', function () {
return view('home');
})->middleware('CustomAuth');
});
但这没用.知道如何确保会话已启动,或者在调用中间件之前启动了该会话吗?我正在使用Laravel 5.3
But this didn't work. Any idea how I can make sure that the session had started, or start it before the middleware is called? I'm using Laravel 5.3
推荐答案
L5中间件由3种类型"组成.
The L5 middleware consists of 3 "types".
可在Kernel.php
文件中找到HTTP请求的配置(通常为App\Http\Kernel
.有一个针对所有请求运行的全局中间件,并在$middleware
中声明了),有一个路由组中间件将针对所有请求运行对于给定的路由组并在$middlewareGroups
中声明,默认情况下,在web.php
中声明的所有路由都被视为web
路由,因此所有Web中间件都适用.
The configuration is found in the Kernel.php
file for HTTP requests (typically App\Http\Kernel
. There's global middleware which will run for all requests and is declared in $middleware
, there's the route group middleware which will run for all requests for a given route group and is declared in $middlewareGroups
, by default all routes declared in web.php
are considered to be web
routes so all the web middleware apply.
第三种是路由中间件.这些以"middlewareName" => Middleware::class
的形式在$routeMiddleware
数组中声明,并且可以在任何路由中使用,例如
The 3rd type is route middleware. These are declared in the $routeMiddleware
array in the form "middlewareName" => Middleware::class
and can be used in any route e.g.
Route::get("/route", function () { /* route body */ })->middleware("middlewareName");
这些按顺序运行> global> group>路由中间件,而SessionStart
中间件作为组中间件的一部分运行.需要访问该会话的任何其他中间件都必须放在SessionStart
中间件之后.
These run in order global > group > route middleware and the SessionStart
middleware runs as part of the group middleware. Any other middleware that needs access to the session will need to be placed after the SessionStart
middleware.
这篇关于在Laravel中的自定义中间件中使用会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!