I'm creating a module that will expose a feed of content (under certain rules) as a JSON response. I want to use a Drupal 8 view to construct a query for that set of content, since it is a complicated set of rules.

Is there a way to query a Drupal 8 view in a custom module and iterate over the results?

Note that I am not trying to modify the output of the View with PHP; I just read the results and package them into a JSON response in my custom module.

I'm looking for something similar to entityQuery where I can instantiate a view object, execute it, and then iterate over the nodes that are in the result set.

Most of the searching I've done here and on Google points to Drupal 7 answers (which might not be relevant to Drupal 8 code), or otherwise generic Drupal query examples (when I am specifically looking for the Views module).

As an example, I'm looking to be able to do something like this (pseudocode):

class MyCustomModuleController {

  public function getFeed() {
    $view = View::get('my_view_name');
    $nodes = $view->execute();
    $response = [];
    foreach ($nodes as $node) {
      $response[] = $node->getSomeField();
    return $response;


1 Answer 1

$view = \Drupal\views\Views::getView('my_view_name');

foreach ($view->result as $row) {
    //dont remeber if $node is fully loaded
    $node = $row->_entity;
    // if not, add this
    $node = Node:load($row->_entity->id());
    $response[] = $node->[FIELD]->view('full'); // full display
return $response;
  • 1
    Can you explain this answer and why you chose to use the Views::getView over View::get?
    – Kevin
    Dec 3, 2017 at 18:10
  • @Kevin I take it's because Views:getView() loads a view and returns its executable object.
    – apaderno
    Dec 3, 2017 at 18:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.