Laravel全球中间件无法获得会话

时间:2017-03-18 17:49:09

标签: php laravel laravel-5.3

 protected $middleware = [
     \App\Http\Middleware\Syspoint::class,
]

use Session;
class Syspoint
{
    echo \Session::get('syspoint');
}

每次页面请求时都需要运行中间件,中间件包含会话。

我放在protected $middleware内,但全局中间件无法获得会话。

2 个答案:

答案 0 :(得分:8)

您正在调用Session但尚未启动。

如果您需要在中间件中使用Session,则必须将其放在密钥protected $middlewareGroups下的属性web中,并在调用StartSession之后,即:

 protected $middlewareGroups
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \App\Http\Middleware\Syspoint::class,

答案 1 :(得分:0)

dparoli的答案正确但不完全正确!因为这个中间件会运行每个Web请求!

如何在某条路线下跑步?这是如何;

protected $routeMiddleware = [
    'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'sys-point' => \App\Http\Middleware\Syspoint::class,
];

然后在你的路线上定义新的中间件

Route::group(['middleware' => ['web','sys-point'], 'namespace' => 'YourControllers'], function()
{
}