简体   繁体   English

在route.php中访问Auth :: user()

[英]Access Auth::user() in route.php

I'm having a problem in accessing the Auth::user() in my route.php. 我在route.php中访问Auth :: user()时遇到问题。 So far here's what i've got: 到目前为止,这是我所拥有的:

Route::group(['middleware' => 'auth'], function () {
    if(Auth::user()->role == "manager"){
        Route::get('/','ManagerController@index');
    }
    else if(Auth::user()->role == "rater"){
        Route::get('/','RaterController@index');
    }
});

It gives me this error "Trying to get property of non-object" whenever I try to use the Auth::user()->role 每当我尝试使用Auth :: user()-> role时,都会出现此错误“试图获取非对象的属性”

Change your code to: 将您的代码更改为:

Route::group(['middleware' => 'auth'], function () {
            if (Auth::check()) {
                if(Auth::user()->role == "manager"){
                    Route::get('/','ManagerController@index');
                }
                else if(Auth::user()->role == "rater"){
                    Route::get('/','RaterController@index');
                }
            }
        });

Because if the current user has not logged in yet, he will not have a role so Auth::user() will return null and thus accessing role property is not possible. 因为如果当前用户尚未登录,那么他将没有role因此Auth::user()将返回null ,因此无法访问role属性。 You need to check first if the user is logged in by using if (Auth::check()) . 您需要先使用if (Auth::check())用户是否登录。

PS Checking the authentication inside the routes file is such a bad practice and should be handled inside a controller . PS检查路由文件中的身份验证是一种不良做法,应在controller内部处理。 Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM