n How to alter existing routes in Drupal 8 | CodimTh

Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh

After building routes (e.g. when a module is enabled or when caches are cleared), the RoutingEvents::ALTER event triggers the route alter process. The \Drupal\Core\Routing\RouteSubscriberBase class contains an event listener that listens to this event. You can alter existing routes by implementing the alterRoutes(RouteCollection $collection) method of this class.

To alter existing routes in Drupal 8 we need to create a service that extends RouteSubscriberBase. Below is how to do it with examples of how to disable the user registration page and user password reset page.

Create the mymodule.info.yml

name: 'My Module'
description: 'Custom Module'
package: Custom
type: module
core: 8.x


Create the mymodule.services.yml file:

    class: Drupal\mymodule\RouteSubscriber
    arguments: []
      - { name: event_subscriber }


Create the src/RouteSubscriber.php Class :

namespace Drupal\mymodule;

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

 * Class RouteSubscriber
 * @package Drupal\mymodule
class RouteSubscriber extends RouteSubscriberBase {

   * @param RouteCollection $collection
  public function alterRoutes(RouteCollection $collection) {

    // Disable access to the registration page.
    if ($route = $collection->get('user.register')) {
      $route->setRequirement('_access', 'FALSE');

    // Remove user password reset page.
    if ($route = $collection->get('user.pass')) {
      $route->setRequirement('_access', 'FALSE');



Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts


Page Facebook