Programmatically checking access on routes

If we defined routes and users go to those routes, Drupal will check access for us automatically (according to the requirements set forth in the route definition). However, we may often need to check access to a given route programmatically, for example, to know whether we should show a link to it to the current user. Drupal is of the opinion that if a user doesn't have access to a route, they should never see a link to it anywhere. So, we should follow suit in our custom code.

In Chapter 2, Creating Your First Module, we saw how to work with the Url objects to create links, and we can use these very Url objects to check access on a given route; consider the following example:

$url = Url::fromRoute('hello_world.hello'); ...

Get Drupal 8 Module Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.