Avoid using `loadByProperties` to load entities

Matt Glaman
2 min readApr 12, 2022

Drupal’s entity storages have a loadByProperties method to simplify loading entities based on conditions. For configuration entities, these are on their properties. For content entities, these are on their field values. It is a common carry-over from the old days of Drupal 7 with entity_load_multiple and the properties condition argument.

There is just one big problem! The loadByProperties method disables entity access checks. That makes this method unsafe and causes it to bypass entity query access checks.

public function loadByProperties(array $values = []) {
// Build a query to fetch the entity IDs.
$entity_query = $this->getQuery();
$entity_query->accessCheck(FALSE);
$this->buildPropertyQuery($entity_query, $values);
$result = $entity_query->execute();
return $result ? $this->loadMultiple($result) : [];
}

The method’s documentation does not specify this fact, either. I am sure this also simplified the migration from Drupal 7 to Drupal 8 for countless projects.

/**
* Load entities by their property values.
*
* @param array $values
* An associative array where the keys are the property names and the
* values are the values those properties must have.
*
* @return \Drupal\Core\Entity\EntityInterface[]
* An array of entity objects indexed by their ids.
*/
public function loadByProperties(array $values = []);

--

--

Matt Glaman

PHP software engineer, open source contributor, and speaker