Check, if a user has access to a route

Posted by patrick on Wed, 03/08/2017 - 08:19

If you want to check, if a user has access to a route, you can use the checkNamedRoute method of the AccessManager. You'll need the name of the route, any route parameters and an AccountInterface object. You could get these from a Route object or provide them directly.

$access_manager = \Drupal::service('access_manager'); 
$has_access = $access_manager->checkNamedRoute($route_name, $route_parameters, $account);

For example, to check, if the current user has access to the canonical display of the Node with the Node Id 9, it would look something like this:

$access_manager = \Drupal::service('access_manager'); 
$has_access = $access_manager->checkNamedRoute('entity.node.canonical', ['node' => 8], \Drupal::currentUser());

If you'd rather want an AccessResult object instead of TRUE or FALSE as the return value, there is a third parameter, that you could set to TRUE to get that.

Systems
Drupal 8