Auth::user() returns null in Laravel 5.2

2019-02-15 07:56发布

问题:

I have searched and found various results like these: auth()->user() is null in Laravel 5.2 and Auth::user() returns null

But, mine is still not working.

Auth::user() works in the controller, but not in the Model. It returns null.

The code is:

public function scopeOwned($query) {
    $query->where('user_id', '=', Auth::user()->id);
}

I tried dd(Auth::user()) and it returns null as well.

Any Idea?

回答1:

Thank you guys.

The problem solved here: https://laracasts.com/discuss/channels/laravel/authuser-returns-null-in-laravel-52

I had to add the stack into middleware directly (not in the group).

in /Http/kernel.php:

protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    \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
];


回答2:

I had a similar problem. I was defining a custom Middleware for the API group and Auth was always appearing as null.

I fixed this by loading in the EncryptCookies Middleware before my custom one.

'api' => [
    \App\Http\Middleware\EncryptCookies::class,
    \App\Http\Middleware\VerifyParametersMiddleware::class, // your custom middleware, load after EncryptCookies
    'throttle:60,1',
    'bindings',
],

This change can be made within Kernel.php.



回答3:

From the same discussion that the accepted answer links to, I found the following solution to work. Edit your /routes/web.php file and surround your existing routes with Route::group('middleware' => 'web']), like so:

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

    Auth::routes();

    // The rest of your routes

});

As far as I understand, this will not have any security or other implications, as it is simply loading the web middleware prior to processing the contained routes. If anyone knows of security or other concerns / ramifications, please post them in the comments on this answer.



回答4:

I have a similar problem with Laravel 5.2, Try to change Auth::user()->id to Auth::id()

public function scopeOwned($query) {
    $query->where('user_id', '=', Auth::id());
}

It's worked for me!