Laravel global middleware can't get session

前端 未结 2 1940
梦毁少年i
梦毁少年i 2021-01-19 20:06
 protected $middleware = [
     \\App\\Http\\Middleware\\Syspoint::class,
]

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

相关标签:
2条回答
  • 2021-01-19 20:40

    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,
    
    0 讨论(0)
  • 2021-01-19 20:41

    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()
    {
    }
    
    0 讨论(0)
提交回复
热议问题