How to check current user in laravel?

by scotty_walker , in category: PHP Frameworks , 5 months ago

How to check current user in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by deron , 5 months ago

@scotty_walker 

To check the current user in Laravel, you can use the auth helper function or the Auth facade.


Using the auth helper function:

1
2
3
4
5
6
7
if (auth()->check()) {
    // User is logged in
    $user = auth()->user();
    // ... do something with $user
} else {
    // User is not logged in
}


Using the Auth facade:

1
2
3
4
5
6
7
8
9
use IlluminateSupportFacadesAuth;

if (Auth::check()) {
    // User is logged in
    $user = Auth::user();
    // ... do something with $user
} else {
    // User is not logged in
}


In both cases, if the check() method returns true, it means the user is currently logged in. You can then retrieve the user instance using the user() method.