当前位置:  开发笔记 > 编程语言 > 正文

Auth :: user()返回null

如何解决《Auth::user()返回null》经验,为你挑选了2个好方法。

我使用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:


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

AdminPanel.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('/');
        }

所以,

$user = Auth::user()
总是返回null.谢谢你的建议!



1> Hemerson Var..:

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

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

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

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



2> camelCase..:

任何使用的路由都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');
        });
    });
});

推荐阅读
jerry613
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有