在Laravel 5.3中,Auth :: guard('user') - > user()为null

时间:2016-11-15 15:22:41

标签: laravel authentication laravel-5 laravel-5.3 guard

我正在尝试传递给所有模板当前用户对象,如下所示:

class Controller extends BaseController
{
    public function __construct()
    {
        view()->share('usr', Auth::guard('user'));
    }
}

每个控制器都由Controller扩展。但是如果我尝试转储Auth::guard('user')->user() Laravel返回null,虽然我已登录。此外,当我将此变量传递给模板时,{{ $usr->user() }}返回当前用户。我做错了什么?

我的config / auth.php

'defaults' => [
    'guard' => 'user',
    'passwords' => 'users',
],
'guards' => [
        'user' => [
            'driver' => 'session',
            'provider' => 'user',
        ],
    ],
'providers' => [
        'user' => [
            'driver' => 'eloquent',
            'model' => App\User::class,
        ],
    ],

Kernel.php

         protected $middleware = [
     \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
 ];

/**
 * The application's route middleware groups.
 *
 * @var array
 */
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,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],

    'api' => [
        'throttle:60,1',
        'bindings',
    ],
];

/**
 * The application's route middleware.
 *
 * These middleware may be assigned to groups or used individually.
 *
 * @var array
 */
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,
];

我自己登录的功能:

public function authorizes(Request $request)
{
        $this->validate($request, [
        'login' => 'required|max:50',
        'password' => 'required|max:50'
    ]);

        $credentials = $request->only(['login', 'password' ]);
        $remember = $request->get('remember', false) == 1 ? true : false;

    if ($this->guard->attempt( $credentials, $remember)) {
        $user = $this->guard->user();
        $user->last_login = date('Y-m-d H:i:s');
        $user->save();
        return redirect()->route( 'homepage' )->withSuccess(trans('app.login.success'));
    }
    return redirect()->back()->withErrors(trans('app.wrong.credentials'));
}

4 个答案:

答案 0 :(得分:3)

在Laravel 5.3中,您应该像这样更改控制器构造函数以使其工作(假设您至少使用Laravel 5.3.4):

public function __construct()
{
    $this->middleware(function ($request, $next) {
        view()->share('usr', Auth::guard('user'));

        return $next($request);
    });
}

您可以在Upgrade guide

中看到此更改
  

在早期版本的Laravel中,您可以访问会话变量或   控制器构造函数中经过身份验证的用户。这是   从来没有打算成为框架的明确特征。在Laravel   5.3,您无法访问控制器构造函数中的会话或经过身份验证的用户,因为中间件尚未运行。

     

作为替代方案,您可以直接定义基于Closure的中间件   在你的控制器的构造函数中。在使用此功能之前,请确保   您的应用程序正在运行Laravel 5.3.4

答案 1 :(得分:2)

尝试这样做:

view()->share('usr', Auth::user());

或者这个:

view()->share('usr', auth()->user());

答案 2 :(得分:0)

首先检查用户是否被记录,然后将当前用户分享为:

public function __construct()
{
    if (auth()->check()) {
        $this->currentUser = auth()->user();
        View::share('currentUser', $this->currentUser);
    } else {
      // you can redirect the user to login page.
    }
}

答案 3 :(得分:0)

在您的情况下,有两件事需要考虑

  1. 要获得实际的用户模型,您应该Auth::guard('user')->user()
  2. 调用Auth::user()时,
  3. view()->share()实际上尚未初始化,请参阅https://github.com/laravel/framework/issues/6130
  4. 因此您可以使用视图编辑器。在boot添加的AppServiceProvider方法中添加:

    \View::composer('*', function ($view) {
        $view->with('usr', \Auth::guard('user')->user());
    });