Laravel 5.2 introduces the middleware groups concept: you can specify that one or more middleware belongs to a group, and you can apply a middleware group to one or more routes
By default Laravel 5.2 defines a group named web
, used to group the middleware handling session and other http utilities:
protected $middlewareGroups = [
'web' => [
AppHttpMiddlewareEncryptCookies::class,
IlluminateCookieMiddlewareAddQueuedCookiesToResponse::class,
IlluminateSessionMiddlewareStartSession::class,
IlluminateViewMiddlewareShareErrorsFromSession::class,
AppHttpMiddlewareVerifyCsrfToken::class,
],
So, if you want session handling, you should use this middleware group for all the routes in which you want to use authentication:
Route::group( [ 'middleware' => ['web'] ], function ()
{
//this route will use the middleware of the 'web' group, so session and auth will work here
Route::get('/', function () {
dd( Auth::user() );
});
});
UPDATE FOR LARAVEL VERSION >= 5.2.27
As of Laravel 5.2.27
version, all the routes defined in routes.php
are using by default the web
middleware group. That is achieved in app/Providers/RouteServiceProvider.php
:
protected function mapWebRoutes(Router $router)
{
$router->group([
'namespace' => $this->namespace, 'middleware' => 'web'
], function ($router) {
require app_path('Http/routes.php');
});
}
So you don't need anymore to add manually the web
middleware group to your routes.
Anyhow, if you want to use the default authentication for a route, you still need bind the auth
middleware to the route
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…