Entity type manager doesn't have access to the random order so we need to use a query to find the node ID and then load it using entity type manager.
$select = \Drupal::database()->select('node_field_data', 'n')
->fields('n', ['nid', 'title'])
->condition('n.status', 1)
->range(0, 1)
->orderRandom();
$results = $select->execute();
$nid = $results->fetchField();
$node = \Drupal::service('entity_type.manager')->getStorage('node')->load($nid);
Add new comment