How to get authenticated user inside a controller?

Viewed 29

I'm writing a social bookmark app, in order to learn Laravel 9.30.1. Every user has a public page accessible via /{userhandle}/, where their public favorites will be displayed. The problem is, there can also be private links, which will be displayed only if the owner is accessing their own page. So, I need to figure it out if the authenticated user owns a given /{userhandle}/ page, in order to know if private links should be listed. Notice that a guest can also access user pages, but will never see any private link.

I'm trying to retrieve the authenticated user inside the UserController class, but both

dd(Auth::user());

and

dd(auth()->user());

return null.

Since the authenticated user is not yet available, I have the feeling that this code is actually in the wrong place, and that it need to be delegated elsewhere. Is that so?

If not, then how can I actually access the authenticated user from a Controller class?

And finally: is there a better way to solve this issue?

1 Answers

Yeah... so it seems that

dd(auth()->user());

Is actually working fine. I was debugging for so long that my session expired, and I didn't noticed...

Related