Drupal - How know if user is visitor or logged member?
For the sake of more robust and descriptive code, you can make use of the handy User::isAnonymous()
method, e.g.
if (\Drupal::currentUser()->isAnonymous()) {
// Anonymous user...
}
$current= \Drupal::currentUser();
if (!$current->id()) {
// is visitor
}
else {
// is logged
}
isAnonymous()
holds the danger of not working when a site is saving data (for example in forms) in PrivateTempStore
. Therefore, i prefer the following:
if (\Drupal::currentUser()->isAuthenticated()) {
// This user is logged in.
} else {
// This user is anonymous.
}