I am trying to retrieve the details of the last user who registered to the site. There is a similar question here: How to get the uid of a newly created user? but it assumes that the registration is also done programmatically, while I don't have any such assumption.

The only way I saw how to do it was to go to the DB directly (not recommended by basically every resource I read). Is there a way to do this through some other interface?

  • I don't know if there is a function offhand, but what is wrong with using a database query? You could also execute a View in code and use the result. – Kevin May 23 '18 at 15:51
  • It's just that everywhere I read, it says I shouldn't use the DB object unless absolutely necessary. Just trying to follow best practices :) – Ynhockey May 23 '18 at 16:18

You don't need to query the DB directly, you can use an entity query:

$uids = \Drupal::entityQuery('user')
  ->sort('created', 'DESC')
  ->range(0, 1)
$uid = reset($uids);

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.