Attempt to read property "usertype" on null

Viewed 60

In my system, there are two different dashboards. One for admin and another one for user. In my database there is a column name usertype and there are two int values. 1 is for the admin and 0 is for the users. In my laravel project if the login user trying to access their dashboard then firstly in controller file it will check if he/she is admin or not. If his/her assigned usertype value is 1 then he/she will redirect to the admin dashboard, if it is not 1 then he/she will redirect to the user dashboard. But I got an error

Attempt to read property usertype on null".

The admincontroller code for dashboard redirection are given below

public function admindashboard(){
    if(Auth::user()->usertype == 1 ){
        return view('admin/pages/admindashboard');
    }
    else{
        return view('viewer.pages.userpanel.userdashboard');
    }
}
2 Answers

Best practice is to make middleware for admin and normal user. But if you want to continue with your existing code, check for Auth::user() also in if condition like this.

public function admindashboard(){
    if(!empty(Auth::user()) && Auth::user()->usertype == 1 ){
        return view('admin/pages/admindashboard');
    }
    return view('viewer.pages.userpanel.userdashboard');
}

You need to use middleware in the controller of each control panel and determine the access level there. The user rights package can help you with this.

Example of use inside the controller:

class AdminDashboardController extends Controller
{
    public function __construct()
    {
        $this->middleware('admin');
    }
}

Example of use inside the blade (without using controller:):

@role('admin')
    <x-panels.admin />
@else
    <x-panels.user />
@endrole
Related