0

I have a site running on Drupal 8 with a login module. I want to get the user ID for the currently logged-in user to later execute a database query.

This is the code I am using.

$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
$uid = $user->get('uid')->value;
echo $uid;

In the controller of a custom module, this code works only between all using and the class controller uses the following code.

namespace Drupal\CoopMatha_adh_apport\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Node\Entity\Node;
use Drupal\CoopMatha_adh_apport\Repository;
use Drupal\matha_tools\Controller\ListeController;
use Drupal\matha_tools\Controller;

$userCurrent = \Drupal::currentUser();
$user = \Drupal\user\Entity\User::load($userCurrent->id());
$uid= $user->get('uid')->value;
echo $uid;  

class RapportsController extends ControllerBase {    

  // I want the user ID here.
  public function filtrer($firstLetter='', $nbr_ligne='') {
    // …
  }

}

How do I get the currently logged-in user ID in the controller class?

0
2

How do I get the currently logged-in user ID in the controller class?

Controllers have a currentUser method:

public function filtrer($firstLetter='', $nbr_ligne='') {
  $current_user_id = $this->currentUser()->id();
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.