简体   繁体   中英

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. 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.

Here is my routes.php file:

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. 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:

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 () {

        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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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