Laravel global middleware can't get session

天涯浪子 提交于 2019-12-01 19:15:30

You are calling Session but it is not already started.

If you need Session inside your middleware you have to put it in the property protected $middlewareGroups under the key web and after the call to StartSession, i.e.:

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

dparoli's answer correct but not exactly! Because this middleware will run every web request!

How about running only under some route? Here is how;

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,
];

Then on your route define new middleware

Route::group(['middleware' => ['web','sys-point'], 'namespace' => 'YourControllers'], function()
{
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!