简体   繁体   English

Laravel 5.1身份验证 - 无法重定向到登录页面

[英]Laravel 5.1 authentication - cannot redirect to login page

Trying to block a route for the guest users. 试图阻止访客用户的路由。 When someone hits localhost:8000/AdminPanel it will check if the user is logged in as an admin or not. 当有人点击localhost:8000/AdminPanel它会检查用户是否以管理员身份登录。 If admin then it works fine, if an agent then it redirects to the login page, but if I hit the link as a guest user, it doesn't redirect me to the login page, instead it shows some error: 如果管理员然后它工作正常,如果代理然后它重定向到登录页面,但如果我作为访客用户点击链接,它不会将我重定向到登录页面,而是显示一些错误:

ErrorException in routes.php line 53: Trying to get property of non-object. routes.php第53行中的ErrorException:尝试获取非对象的属性。

Here is my routes.php file: 这是我的routes.php文件:

Route::get('/AdminPanel', function () {
    if (Auth::user()->user_type_id == 1) { // line 53
        return view('frontend.AdminPanel');       
    }

    if (Auth::user()->user_type_id == 2) {
        return view('auth/login');
    }

    if (Auth::guest()) {
        return view('auth/login');
    }
});

This is because if a user is not logged in Auth::user() is null. 这是因为如果用户未登录Auth :: user()为null。 So it throws the error that its trying to get property of a non object. 所以它抛出了它试图获取非对象属性的错误。 You should first check is Auth is set, like this: 您应首先检查Auth是否已设置,如下所示:

if(Auth::check()){
    if(Auth::user()->user_type_id==1){    //line 53
            return view('frontend.AdminPanel');       
    }
    else if(Auth::user()->user_type_id==2){
            return view('auth/login');
    }
}
else{ 
    return view('auth/login');
}

Why not try with this ? 为什么不尝试这个? Route::get('/AdminPanel', function () { Route :: get('/ AdminPanel',function(){

        if(Auth::user()->user_type_id==1){    //line 53
            return view('frontend.AdminPanel');       
        }
        elseif(Auth::user()->user_type_id==2){
            return view('auth/login'); 
        }else{
            return view('auth/login');
        }

    })

so user type id 2 and guest user would redirect to login page? 所以用户输入id 2和guest用户会重定向到登录页面?

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

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