Check if user authenticated?

Published 1 month ago by GTHell

How do I check if user authenticated? Google result is not helpful since 90% of the answers is to use auth middleware. Lol, I want to perform some query on homepage if user authenticated.

Best Answer (As Selected By GTHell)
adrian.nuernberger

@GTHell You can also use the helper function

auth()->check()
Cronix
Cronix
1 month ago (727,800 XP)

Hmm, sounds like something that might be in the docs?

To determine if the user is already logged into your application, you may use the check method on the Auth facade, which will return true if the user is authenticated:

use Illuminate\Support\Facades\Auth;

if (Auth::check()) {
    // The user is logged in...
}

https://laravel.com/docs/5.6/authentication#retrieving-the-authenticated-user

jlrdw
jlrdw
1 month ago (244,950 XP)

Laravel has documentation?

GTHell

Oh, I just found out the main problem is it's an AJAX. On normal controller that pass through web.php can detect the Auth::check() but the same controller with api.php return false upon calling Auth::check(). What am I suppose to do in this scenario? My frontend is using Vue component and I'm calling axios in vuex.

jlrdw
jlrdw
1 month ago (244,950 XP)

That reminds me of Paul Harvey I used to listen to him on the radio.

now the rest of the story

I don't use an API Cronix will probably answer but you need token-based Authentication.

Many tutorials available.

Danlog

If you want to check it on the view, you do @if(Auth::check())

now let's get deeper...

@if(Auth::check())
//HERE IS WHAT WILL APPEAR IF THE USER IS LOGGED IN
@else 
//HERE IS WHAT WILL APPEAR IF THE USER IS NOT LOGGED IN
@endif 

as easy as that.

GTHell

@jlrdw I'm not doing authentication. I just learnt that just call the ajax in the web.php instead of api.php and have the if(request()->ajax()) to check if it ajax request. Now a GET controller can serve as both ajax and normal http request and Auth::check() work now because now it's session instead of request from api.php.

Thank for all the answers though.

adrian.nuernberger

@GTHell You can also use the helper function

auth()->check()

Please sign in or create an account to participate in this conversation.