Skip to main content

How to get the current user or load a user using a uid value.

$current_user = \Drupal::currentUser();
$user = \Drupal\user\Entity\User::load($current_user->id());

or just use

$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());

An example of this in action

/**
 * Change the display of the user's name.
 *
 * @param int $uid
 *   User id.
 *
 * @return string
 *   User name.
 */
function change_users_name($uid) {
	// status of the current user
	$logged_in = \Drupal::currentUser()->isAuthenticated();
	$author = \Drupal\user\Entity\User::load($uid);
	$first_name = $author->get('field_firstname')->value;
	$last_name = $author->get('field_lastname')->value;
	$user_url = Url::fromRoute('user.page', ['user' => $author->id()]);
	$link = Link::fromTextAndUrl($last_name, $user_url)->toString();

	return ($logged_in) ? $link : $first_name . " " . $last_name;
}

 

This can be further reduced where the line

$author = \Drupal\user\Entity\User::load($uid);

Becomes

$author = User::load($uid);

To make this change, you'll need to add at the top of the file

<?php

// ... other use references ... //
use Drupal\user\Entity\User;

 

Related articles

Andrew Fletcher04 Apr 2025
Managing .gitignore changes
When working with Git, the .gitignore file plays a critical role in controlling which files and folders are tracked by version control. Yet, many developers are unsure when changes to .gitignore take effect and how to manage files that are already being tracked. This uncertainty can lead to...
Andrew Fletcher26 Mar 2025
How to fix the ‘Undefined function t’ error in Drupal 10 or 11 code
Upgrading to Drupal 10.4+ you might have noticed a warning in their code editor stating “Undefined function ‘t’”. While Drupal’s `t()` function remains valid in procedural code, some language analysis tools — such as Intelephense — do not automatically recognise Drupal’s global functions. This...
Andrew Fletcher17 Mar 2025
Upgrading to PHP 8.4 challenges with Drupal contrib modules
The upgrade from PHP 8.3.14 to PHP 8.4.4 presents challenges for Drupal 10.4 websites, particularly when dealing with contributed modules. While Drupal core operates seamlessly, various contrib modules have not yet been updated to accommodate changes introduced in PHP 8.4.x. This has resulted in...