If I have a node object I can use $node->getCacheTags() to get the cache tags for the node object, and I can do the same for other entities. Is there a way for me to do something similar with a Route object?

$cache_tags = $route->getCacheTags();

or maybe there's a way for me to do something like this, where $entity is populated with the $user, or $node, or $view, etc. object that is responsible for the current route:

$entity = $route->getEntity();
$cache_tags = $entity->getCacheTags();

1 Answer 1


Adding my eventual solution based on @No Sssweat's comment.

I created a method in a service like:

public function getEntityFromRoute(RouteMatchInterface $route_match) {
  foreach ($route_match->getParameters() as $param) {
    if ($param instanceof EntityInterface) {
      return $param;

  return FALSE;

Then I have code like the following where I'm not entirely sure what entity type may be providing the route:

$route_entity = $MY_SERVICE->getEntityFromRoute(\Drupal::routeMatch());
$cache_tags = [];
if ($route_entity !== FALSE) {
  $cache_tags = $route_entity->getCacheTags();

Then I create my render array using the cache tags.

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.