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?