Sling Academy
Home/PHP/Laravel: How to retrieve authenticated user

Laravel: How to retrieve authenticated user

Last updated: January 16, 2024

Introduction

Laravel is known for its elegant syntax and provides a robust set of tools to manage authentication out of the box. One common task in building applications is to retrieve details of the currently authenticated user. This tutorial will walk you through the various methods Laravel offers for accessing the authenticated user, from basic examples to more advanced cases.

Retrieving User with Facades

The simplest way to get the currently authenticated user in Laravel is using the Auth facade.

$user = Auth::user();
// You now have access to the authenticated user object.

This will return an instance of the authenticated user model or null if no user is authenticated.

Authenticating with Helpers

Laravel provides a helpful helper function to achieve the same as above.

$user = auth()->user();
// The auth helper function is a convenient wrapper around the Auth facade.

Dependency Injection & Route Models

If you’re working in a controller, you can access the authenticated user by type-hinting the Illuminate\Http\Request object in your method and calling user() on it.

public function profile(Request $request)
{
    $user = $request->user();
    // Your logic here
}

Middleware

If you want to retrieve the authenticated user only on certain routes, you might want to use the auth middleware. It ensures that your route or controller logic is only reached when a user is authenticated.

Route::get('/profile', function () {
    // Only authenticated users may enter...
})->middleware('auth');

In controller methods, you can use middleware in the constructor.

public function __construct()
{
    $this->middleware('auth');
}

public function show()
{
    $user = auth()->user();
    // Authenticated user logic
}

Using API Tokens

With the advent of API-based development, Laravel supports token authentication out of the box. It’s common to use the api middleware in conjunction with tokens to authenticate users on API routes.

// Using Laravel Sanctum
Route::middleware('auth:sanctum').get('/user', function (Request $request) {
    return $request->user();
});

Checking for User Authentication

Sometimes, you’ll want to check if a user is logged in without retrieving the user. Laravel makes this straightforward.

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

Retrieving User by Guard

If your application implements multiple guards, you may need to specify which guard to use when retrieving an authenticated user.

$admin = Auth::guard('admin')->user();
// This will retrieve the user authenticated by the 'admin' guard.

Accessing User Properties & Relationships

Once you have the authenticated user, you can access its properties and methods just like any other Eloquent model.

$name = $user->name;
$orders = $user->orders; // Assuming the User model has an 'orders' relationship.

Advanced User Requests

In more advanced scenarios, you might want to inject the user model directly into your controller methods. This is easily accomplishable by type-hinting the user model assuming your route is set up correctly.

// web.php
Route::get('/profile', 'ProfileController@show');

// ProfileController.php
public function show(User $user)
{
    // The User model is automatically injected here
}

Conclusion

In this tutorial, we’ve covered the basics of retrieving the authenticated user in a Laravel application, through to more complex scenarios involving multiple guards and API token authentication. By harnessing the power of Laravel’s authentication facilities, you can ensure that user retrieval is done efficiently and securely.

Next Article: Authorization Role in Laravel: A Practical Guide

Previous Article: Laravel: How to Log Out a User (Basic & Advanced Techniques)

Series: Laravel & Eloquent Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array