programmatically get all nodes from drupal 8

12,096

This actually returns node objects

$nodes =  \Drupal\node\Entity\Node::loadMultiple($nids); 

perhaps your output gives minimal results and not objects. If you inspect with a proper debugger you will see the objects.

Perhaps its better to actually get one node object at a time if you expect too many nodes to be returned from the query

$query = \Drupal::entityQuery('node')
  ->condition('status', 1) //published or not
  ->condition('type', 'news') //content type
  ->pager(10); //specify results to return
$nids = $query->execute();

foreach ($nids as $nid) {
  $node = \Drupal\node\Entity\Node::load($nid); 
  $body = $node->body->value;
  $title = $node->title->value;
  //...
}  
Share:
12,096

Related videos on Youtube

khaled
Author by

khaled

Updated on June 04, 2022

Comments

  • khaled
    khaled about 2 years

    I am trying to get all nodes of a certian type from drupal. I have tried many ways to achieve that, but maybe due to my lack of Drupal custom module programming experience I couldn't achieve my desire. the closest way that I found on the web, is this:

        $nids = \Drupal::entityQuery('node')->condition('type','news')->execute();
        $nodes =  \Drupal\node\Entity\Node::loadMultiple($nids); 
    
    • the first line returns an object of id's
    • the second line returns the nodes of those id's

    this looks easy and straight forward. but, this is the output! { "59": { "in_preview": null }, "61": { "in_preview": null } }

    can someone please help, what is wrong? and is this the correct way to do it ?

    I want to take the nodes then search every one of them ( I am making some sort of search engine) so I expect some kind of an object that I can then extract the heading, body ... etc, from. is this the correct way ?

  • khaled
    khaled almost 6 years
    Thank you, This did the trick. but can i ask you, what do you mean by inspecting with a proper debugger. i need to know the structure of the node object, can you tell me?
  • GiorgosK
    GiorgosK almost 6 years
    I consider xdebug to be a PROPER debugger but it might be a headache to setup with your favorite code editor (vscode, atom, netbeans, phpstorm etc) ... Perhaps the easiest way to inspect variables in drupal is using kint() which is probably good enough for your purpose ... read more drupal.org/docs/8/theming/twig/…
  • Saf
    Saf over 4 years
    $title = $node->title->value; this is great but how to retrieve the translation based on interface language
  • wranvaud
    wranvaud over 3 years
    Entity query service will be deprecated see: drupal.org/node/2849874