Altering the existing routes in Drupal 8

Sometimes we need to do it. In Drupal 7 it was possible through hook_menu_alter. Let's sort out how to do it in Drupal 8.

Primarily create the class for Route Subscriber. It has to be located in YOUR_MODULE/src/Routing/RouteSubscriber.php

Let's try to alter the access callback:


 * @file
 * Contains \Drupal\my_module\Routing\RouteSubscriber.

namespace Drupal\my_module\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

 * Listens to the dynamic route events.
class RouteSubscriber extends RouteSubscriberBase {

   * {@inheritdoc}
  protected function alterRoutes(RouteCollection $collection) {
    if ($route_item = $collection->get('my_route')) {
      $requirements = $route_item->getRequirements();
      $requirements['_custom_access'] = '\Drupal\my_module\Access\MyModuleAccessCheck::AllowToSeeContent';

Here we will remove the access checking by permission and use our own access checking.

To enable your RouterSubscriber, you should define it in

    class: Drupal\my_module\Routing\RouteSubscriber
      - { name: event_subscriber }

As you can see, it's pretty easy.