How to Get Logged in User Data in Laravel
How to Get Logged in User Data in Laravel

How to Get Logged in User Data in Laravel

In this article, we will go through the steps needed to retrieve the logged-in user data in a Laravel application. By the end of this tutorial, you will know how to access user information in different parts of your Laravel application. This guide is beginner-friendly, using simple language and easy-to-follow code examples.

Prerequisites

Before we start, ensure you have the following:

  • A Laravel project set up
  • User authentication implemented (you can use Laravel’s built-in authentication)

Step 1: Setting Up Authentication

If you haven’t set up authentication in your Laravel application yet, you can do so quickly by running the following command:

composer require laravel/ui
php artisan ui vue --auth
npm install && npm run dev
php artisan migrate

This will set up the basic authentication system with login, registration, and password reset functionality.

Step 2: Retrieving Logged in User Data

Laravel provides a simple way to get the authenticated user data using the Auth facade. Here’s how you can do it in different scenarios:

In a Controller

To get the logged-in user’s information in a controller, you can use the Auth facade as shown below:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class UserController extends Controller
{
    public function showProfile()
    {
        // Get the logged-in user
        $user = Auth::user();

        // Access user information
        $name = $user->name;
        $email = $user->email;

        // Pass user data to a view
        return view('profile', compact('user'));
    }
}

In a Blade Template

To access the logged-in user data directly in a Blade template, you can use the auth helper:

<!DOCTYPE html>
<html>
<head>
    <title>User Profile</title>
</head>
<body>
    <h1>Welcome, {{ auth()->user()->name }}!</h1>
    <p>Email: {{ auth()->user()->email }}</p>
</body>
</html>

In a Middleware

Sometimes, you might need to access the logged-in user data in middleware. Here’s how you can do it:

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class CheckUserRole
{
    public function handle($request, Closure $next)
    {
        // Get the logged-in user
        $user = Auth::user();

        // Check user role
        if ($user->role != 'admin') {
            return redirect('/');
        }

        return $next($request);
    }
}

Step 3: Using Route Middleware

If you want to ensure only authenticated users can access certain routes, you can use route middleware. Laravel provides an auth middleware out of the box. Here’s how you can apply it to your routes:

use Illuminate\Support\Facades\Route;

Route::get('/profile', [UserController::class, 'showProfile'])->middleware('auth');

Step 4: Customizing User Data

You might need to add additional information to the user model. To do this, you can update the User model and add new fields to the users table:

  1. Create a migration to add new columns to the users table:
php artisan make:migration add_details_to_users_table --table=users
  1. In the migration file, add the new columns:
public function up()
{
    Schema::table('users', function (Blueprint $table) {
        $table->string('phone')->nullable();
        $table->string('address')->nullable();
    });
}

public function down()
{
    Schema::table('users', function (Blueprint $table) {
        $table->dropColumn('phone');
        $table->dropColumn('address');
    });
}
  1. Run the migration:
php artisan migrate
  1. Update the User model to include the new fields:
namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use Notifiable;

    protected $fillable = [
        'name', 'email', 'password', 'phone', 'address',
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];
}

Conclusion

Retrieving the logged-in user data in Laravel is straightforward thanks to the Auth facade and various helpers provided by the framework. Whether you need to access user information in controllers, Blade templates, or middleware, Laravel makes it easy to get the data you need.

By following this guide, you should now be able to get logged-in user data and use it in different parts of your Laravel application. Feel free to customize and extend the user model to fit your application’s needs.