Laravel 5.2 验证不工作

Laravel 5.2 Auth not Working

你们知道 Laravel 5.2 是几天前发布的。我正在尝试这个新版本。我在 CLI 上使用以下命令创建了一个新项目:

laravel new testapp

根据documentation of Authentication Quickstart,我按照以下命令构建路由和身份验证视图:

php artisan make:auth

它运行良好。注册工作正常。但是我在登录时遇到问题。登录后,我在 route.php 文件中测试了以下内容:

   Route::get('/', function () {
    dd( Auth::user());
    return view('welcome');
});

Auth::user() 正在返回 null 并且 Auth::check()Auth::guest() 无法正常工作。我通过制作新项目一次又一次地尝试同样的事情两次三次,但无法获得正确的结果。

下面是完整的route.php

    <?php

/*
|--------------------------------------------------------------------------
| Routes File
|--------------------------------------------------------------------------
|
| Here is where you will register all of the routes in an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/

Route::get('/', function () {
    dd( Auth::());
    return view('welcome');
});

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| This route group applies the "web" middleware group to every route
| it contains. The "web" middleware group is defined in your HTTP
| kernel and includes session state, CSRF protection, and more.
|
*/

Route::group(['middleware' => ['web']], function () {
    //
});

Route::group(['middleware' => 'web'], function () {
    Route::auth();

    Route::get('/home', 'HomeController@index');
});

谁能帮帮我?或者有人面临同样的问题吗?我该如何解决?

Laravel 5.2引入middleware groups概念:可以指定一个或多个中间件属于一个组,可以将一个中间件组应用到一个或多个路由

默认Laravel 5.2定义了一个名为web的组,用于对中间件处理会话和其他http实用程序进行分组:

protected $middlewareGroups = [
'web' => [
    \App\Http\Middleware\EncryptCookies::class,
    \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
    \Illuminate\Session\Middleware\StartSession::class,
    \Illuminate\View\Middleware\ShareErrorsFromSession::class,
    \App\Http\Middleware\VerifyCsrfToken::class,
],

所以,如果你想要会话处理,你应该为你想要使用身份验证的所有路由使用这个中间件组

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

更新 LARAVEL 版本 >= 5.2.27

从Laravel 5.2.27版本开始,routes.php中定义的所有路由默认使用web中间件组。这是在 app/Providers/RouteServiceProvider.php :

中实现的
protected function mapWebRoutes(Router $router)
{
    $router->group([
        'namespace' => $this->namespace, 'middleware' => 'web'
    ], function ($router) {
        require app_path('Http/routes.php');
    });
}

因此您不再需要手动将 web 中间件组添加到您的路由中。

总之,如果你想对一个路由使用默认认证,你还需要在路由上绑定auth中间件