Using session in custom middleware in laravel

。_饼干妹妹 提交于 2020-01-03 04:48:09

问题


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');

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');
});

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


回答1:


The L5 middleware consists of 3 "types".

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.

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");

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.



来源:https://stackoverflow.com/questions/42652548/using-session-in-custom-middleware-in-laravel

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