Laravel global middleware can't get session

不想你离开。 提交于 2019-12-19 21:19:51

问题


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

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

I have a middleware required run everytime when page request, the middleware contain session.

I place inside of protected $middleware, but global middleware not able to get session.


回答1:


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,



回答2:


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()
{
}


来源:https://stackoverflow.com/questions/42877799/laravel-global-middleware-cant-get-session

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!