问题
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