php Auth::user() 返回 null

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35160144/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:22:30  来源:igfitidea点击:

Auth::user() returns null

phpauthenticationlaravel-5middleware

提问by imladris

I use Laravel 5.2 and have a problem with middleware. There is the code in the routes.php

我使用 Laravel 5.2 并且中间件有问题。在routes.php中有代码

    use Illuminate\Contracts\Auth\Access\Gate;


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

        Route::auth();

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


    Route::group(['prefix'=>'admin',  'middleware' => 'admin'], function(){
        Route::get('/', function(){
            return view('admin.index');
        });
        Route::get('/user', function(){
            return view('admin.user');
        });
    });

Kernel.php:

内核.php:

    protected $routeMiddleware = [
    ...
     'admin' => \App\Http\Middleware\AdminPanel::class,
    ];

AdminPanel.php

管理面板.php

    namespace App\Http\Middleware;


    use Closure;
    use Illuminate\Support\Facades\Auth;
    use App\Role;

    class AdminPanel
    {
        public function handle($request, Closure $next)
        {
            $user = Auth::user();
            dd($user);

            if($user){
                $role = Role::whereName('admin')->first();
                if($user->hasRole($role)){
                    return $next($request);
                }
            }
            return redirect('/');
        }

So,

所以,

$user = Auth::user()
总是返回空值。感谢您的建议!

回答by Hemerson Varela

I faced a situation where Auth::user()always returns null, it was because I was trying to get the Userin a controller's constructor.

我遇到了Auth::user()总是返回的情况null,这是因为我试图User在控制器的构造函数中获取 。

I realized that you can't access the authenticated user in your controller's constructor because the middleware has not run yet.

我意识到您无法在控制器的构造函数中访问经过身份验证的用户,因为中间件尚未运行。

As an alternative, you can define a Closure based middleware directly in your controller's constructor.

作为替代方案,您可以直接在控制器的构造函数中定义基于闭包的中间件。

namespace App\Http\Controllers;

use App\User;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;

class ProjectController extends Controller
{
    protected $user;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware(function ($request, $next) {

            $this->user = Auth::user();

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

回答by camelCase

Any route that uses Auth()must be encapsulated in the webmiddleware. You're close, just move your Route::group(['prefix' => 'admin'], ...)into the group above.

任何使用的路由都Auth()必须封装在web中间件中。你很接近,只需将你Route::group(['prefix' => 'admin'], ...)移到上面的组中。

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

    Route::auth();

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

    // Moving here will ensure that sessions, csrf, etc. is included in all these routes
    Route::group(['prefix'=>'admin',  'middleware' => 'admin'], function(){
        Route::get('/', function(){
            return view('admin.index');
        });

        Route::get('/user', function(){
            return view('admin.user');
        });
    });
});

回答by Arvid de Jong

I had the same problem because i did not set the table name.

我有同样的问题,因为我没有设置表名。

/**
 * The table associated with the model.
 *
 * @var string
 */
protected $table = 'users';