I am trying to upgrade a Laravel project from Laravel 5.1 to 5.8. I noticed that instead of Auth::user()
, Auth::user()->user()
has been used in the project, and in Laravel 5.8 I get a null exception in some cases because Auth::user
is null. Shall I replace all instances of Auth::user()->user()
with Auth::user()
?
Asked
Active
Viewed 806 times
0

Farzan Badakhshan
- 373
- 1
- 5
- 19
3 Answers
3
You should either use this-
Auth::user();
Or this-
auth()->user();
Please make sure that you have no method/relation with name user() in your user model which may be the reason you have user()->user() like syntax. If that's not the case then feel free to replace it with auth()->user()

Pankaj
- 698
- 9
- 21
-
Care to explain why `auth()->user();` would be a better syntax over the other one? – AntoineB Mar 03 '19 at 16:14
-
It does not give any advantage over Auth::user() other than being fluent. That's why I find (prefer) it better. Laravel is all about fluent syntaxes. – Pankaj Mar 03 '19 at 16:16
1
If Auth:user()
is null, that means that the system didn't get an authenticated user.
But if you want to get the authenticated user you should to use Auth::user()
or auth()->user()
thats retrive the User
model

Fran G S
- 107
- 4
1
Check your route if you added the auth middleware and try using this code.
auth()->user();
and that will retreive the authenticated user same as Auth::user();

Jesus Erwin Suarez
- 1,571
- 16
- 17