By confusedGFCI

2018-03-09 00:56:31 8 Comments

How do I write the following Drupal 8 EntityQuery so that it only returns nodes that the current user has access to?

$query = \Drupal::entityQuery('node')
  ->condition('type', 'article');

The above query will return all nodes, even unpublished ones. Depending on how you use the results (like a list of nodes), users could see titles or other information from unpublished nodes.

$query = \Drupal::entityQuery('node')
  ->condition('type', 'article')
  ->condition('status', 1);

When I add the "status" condition, I now get a list of only published nodes. But I would like people with administer nodes permission to see all the nodes.

Basically, is there a way to simulate the "admin or published" filter, like on Views?


@Berdir 2018-03-09 02:27:43

Entity queries by default consider the node grants system, you actually have to opt out of that to get everything when using node grants.

The problem is that drupal core doesn't actually implement that API for the status, that only becomes relevant when using modules that do.

So unfortunately, the only way to simulate "admin or published" is to do it yourself. Check the permission, if the user doesn't have it, add the status = 1 condition. Note that views uses "administer nodes" but technically, that's actuallly wrong, "bypass node access" would make more sense, that would be consistent with what is being checked when trying to access node/ID of an unpublished node. But in your own code, you can use whatever makes sense for you, including a custom permission.

Alternatively, you could use a module like, which does populate grant records and your entity query will just work. In fact, I just closed a bug report where someone reported the behavior you want as a bug when using that module:

Related Questions

Sponsored Content

1 Answered Questions

Why I cannot get translated entities

1 Answered Questions

View not displayed for other roles

2 Answered Questions

[SOLVED] entityQuery to get Nodes referenced by other nodes like an SQL JOIN

  • 2018-05-23 17:54:36
  • The Unknown Dev
  • 3061 View
  • 4 Score
  • 2 Answer
  • Tags:   8 database

3 Answered Questions

How do I get the list of nodes of a specific content type and their titles?

  • 2017-02-20 12:35:32
  • Robin
  • 60 View
  • 1 Score
  • 3 Answer
  • Tags:   entities

2 Answered Questions

[SOLVED] How to give anonymous users access to only certain nodes?

  • 2016-12-19 13:37:30
  • jjei
  • 2037 View
  • 2 Score
  • 2 Answer
  • Tags:   7 nodes users

2 Answered Questions

[SOLVED] Programmatically publishing and unpublishing nodes: anonymous access

4 Answered Questions

[SOLVED] Allow people to administer only on certain content type?

  • 2012-02-16 09:48:15
  • gilzero
  • 3211 View
  • 6 Score
  • 4 Answer
  • Tags:   users

Sponsored Content