在route.php中访问Auth :: user() [英] Access Auth::user() in route.php

查看:69
本文介绍了在route.php中访问Auth :: user()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的route.php中访问Auth :: user()时遇到问题.到目前为止,这是我所拥有的:

I'm having a problem in accessing the Auth::user() in my route.php. 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');
    }
});

每当我尝试使用Auth :: user()-> role时,都会出现此错误试图获取非对象的属性"

It gives me this error "Trying to get property of non-object" whenever I try to use the Auth::user()->role

推荐答案

将代码更改为:

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

因为当前用户尚未登录,所以他将没有role,因此Auth::user()将返回null,因此无法访问role属性.您需要首先检查用户是否使用if (Auth::check())登录.

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. You need to check first if the user is logged in by using if (Auth::check()).

P.S.检查路由文件中的身份验证是一种不良做法,应在controller内部处理.希望这会有所帮助.

P.S. Checking the authentication inside the routes file is such a bad practice and should be handled inside a controller. Hope this helps.

这篇关于在route.php中访问Auth :: user()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆