When a user register or logged in successfully, the application will create a session to store current logged in data for user. Sometimes to check user role or some logged info then we need current logged in user data.
In Laravel there are two ways to manipulate current user logged in data, we use Auth
facade and auth()
helper. So in this tutorial I will show very basic example where you can access user data after logged in. You can call those facade and helper in Controller file and View in below examples.
The below controller file using helper class auth() to access user logged in data
<?php
namespace App\Http\Controllers;
class UserController extends Controller
{
public function index()
{
// To see all data in current logged in user
$u= auth()->user();
print_r($u);
// To get user id in current logged in data
$uid= auth()->user()->id;
print_r($uid);
// To get user name in current logged in data
$u_name = auth()->user()->name;
print_r($userName);
// To get user email in current logged in data
$u_email = auth()->user()->email;
print_r($u_email);
// To get user created date in current logged in data
$u_created = auth()->user()->created_at;
print_r($u_created);
}
}
How we use facade class named Auth to access user info data in controller file.
<?php
namespace App\Http\Controllers;
use Auth;
class UserController extends Controller
{
public function index()
{
// To see all data in current logged in user
$u= Auth::user();
print_r($u);
// To get user id in current logged in data
$uid= $u->id;
print_r($uid);
// To get user name in current logged in data
$u_name = $u->name;
print_r($userName);
// To get user email in current logged in data
$u_email = $u->email;
print_r($u_email);
// To get user created date in current logged in data
$u_created = $u->created_at;
print_r($u_created);
}
}
We also can use auth
helper class in view (blade file) as well.
<!DOCTYPE html>
<html>
<head>
<title>Hello, World!</title>
</head>
<body>
<h3> User Name: {{ auth()->user()->name }} </h3>
<p> User ID: {{ auth()->user()->id }} </p>
<p> User Email: {{ auth()->user()->email }} </p>
</body>
</html>
We also can use facade
class in view (blade file) as well.
<!DOCTYPE html>
<html>
<head>
<title>Hello, World!</title>
</head>
<body>
<h3> User Name: {{ Auth::user()->name }} </h3>
<p> User ID: {{ Auth::user()->id }} </p>
<p> User Email: {{ Auth::user()->email }} </p>
</body>
</html>
Hope this short article would help you. Have a nice day!!!
You might also like...
Laravel PHPAs the founder and passionate educator behind this platform, I’m dedicated to sharing practical knowledge in programming to help you grow. Whether you’re a beginner exploring Machine Learning, PHP, Laravel, Python, Java, or Android Development, you’ll find tutorials here that are simple, accessible, and easy to understand. My mission is to make learning enjoyable and effective for everyone. Dive in, start learning, and don’t forget to follow along for more tips and insights!. Follow him