Benubird
Benubird

Reputation: 19487

Laravel: How to find if a user is logged in, without forcing a redirect?

I've just discovered that the Auth facade will only work if the auth middleware is included. Unfortunately, including the auth middleware forces the user to redirect if they are not logged in. Which means that routes will either work only for logged in users, or only for non-logged-in users.

I want to have a single page, which can be visited regardless of whether the user is logged in or not, but which displays some additional data from the user object if they are. How do I do this?

It looks like the simplest method will be to create two routes, which are both backed by the same controller method. Is this the best way to do this?

Edit: With further investigation, I've discovered the problem is that the default guard is not the one the user logged in with, and I'm able to get the logged in user auth Auth::guard()->user() instead of Auth::user(). I can't change the default guard globally, so the question becomes: is there a way to set the default guard on a per-route basis? Or do I need to use auth::guard() everywhere?

Upvotes: 0

Views: 2726

Answers (2)

Darragh Blake
Darragh Blake

Reputation: 248

You can use Auth::check()

if($user = Auth::check())
{
    echo 'logged in';
}else{
    echo 'not logged in';
}

Upvotes: 0

madalinivascu
madalinivascu

Reputation: 32354

Use Auth::check() in your view to check if the user is logged in

Upvotes: 6

Related Questions