mrobbizulfikar
mrobbizulfikar

Reputation: 461

Laravel 5.7 : Trying to get property 'role' of non-object

I'm get :

Trying to get property 'role' of non-object (View: E:\xampp\htdocs\demo\resources\views\pages\home.blade.php)

I created a project, there I created admin + user 'role' for login permissions and immediately redirected to home.blade.php.

in home.blade.php I add the following syntax :

@if(Auth::user()->role == 'admin')
<meta http-equiv="REFRESH" content="0;url=admin">
@else
<p>Hello!</p>
@endif

My goal is for the admin to enter the home page and redirect to admin page, and the user to enter the home page only.

My Problem is : If access home.blade.php without login, i get an error like this :

Trying to get property 'role' of non-object (View: E:\xampp\htdocs\demo\resources\views\pages\home.blade.php)

Upvotes: 2

Views: 2684

Answers (1)

matticustard
matticustard

Reputation: 5149

When you are not logged in, the user is null (a non-object).

You can account for this by checking to see if a user is logged in before attempting to access its attributes.

@if(Auth::check() && Auth::user()->role === 'admin')

Upvotes: 3

Related Questions