Share this
if you want to check the user is logged in or not, you can use the Auth
facade or the auth()
helper function. Here’s how you can do it:
1. Use the Auth
Facade
The Auth::check()
method returns true
if the user is logged in, and false
if the user is not logged in.
use Illuminate\Support\Facades\Auth; if (Auth::check()) { // User is logged in return "User is logged in."; } else { // User is not logged in return "User is not logged in."; }
2. Use the auth()
Helper
You can get the same results by using the auth()
helper.
if (auth()->check()) { // User is logged in return "User is logged in."; } else { // User is not logged in return "User is not logged in."; }
3. In Blade Views
To conditionally check the user’s login status in Blade templates, use the following code:
@if(Auth::check()) <p>User is logged in.</p> @else <p>User is not logged in.</p> @endif
Alternatively, use auth()
:
@if(auth()->check()) <p>User is logged in.</p> @else <p>User is not logged in.</p> @endif
4. Middleware Approach
To make sure routes are only accessible to logged-in users, use Laravel’s auth
middleware. Define it in your routes:
Route::get('/dashboard', function () { return view('dashboard'); })->middleware('auth');
For routes that should only be accessible to guests, use the guest
middleware:
Route::get('/login', function () { return view('login'); })->middleware('guest');
5. Checking the Authenticated User’s Data
If you want to get the logged-in user’s details, use the Auth::user()
or auth()->user()
:
$user = Auth::user(); // or auth()->user(); if ($user) { return "Logged-in user: " . $user->name; } else { return "No user is logged in."; }
Ravindra is a passionate full stack developer and dedicated blogger with a flair for crafting user-friendly web applications and insightful articles. With expertise spanning front-end and back-end technologies, Ravindra brings ideas to life through innovative coding solutions.