1

I'm trying to send a redirect after logout, but it is not sending properly. I tried using the hook_user_logout in a module as follows:

use Drupal\Core\Routing\TrustedRedirectResponse;

function module_user_logout($account) {
  $redirect = new TrustedRedirectResponse($url);
  $redirect->send();
}

The send() call causes the page to crash with the message: "The __ page isn't working"

2
  • 1
    maybe because the $url is empty ? Or maybe because you need to add return at the end of the function. Cheers
    – Denis K
    Commented Jul 21, 2016 at 23:20
  • To add what @DenisK said, hook_user_logout() implementations aren't supposed to redirect users. That would not allow other hook_user_logout() implementations to be invoked.
    – apaderno
    Commented Jan 10, 2023 at 8:59

1 Answer 1

3

To resolve current issue we need to create RouteSubscriber my_custom/src/EventSubscriber/MyCustomRouteSubscriber.php :

<?php

namespace Drupal\my_custom\EventSubscriber;

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

    /**
     * MyCustom Route subscriber.
     */
    class MyCustomRouteSubscriber extends RouteSubscriberBase {

      /**
       * {@inheritdoc}
       */
      public static function getSubscribedEvents() {
        $events = parent::getSubscribedEvents();
        $events[RoutingEvents::ALTER] = ['onAlterRoutes', -300];
        return $events;
      }

      /**
       * {@inheritdoc}
       */
      protected function alterRoutes(RouteCollection $collection) {
        if ($route = $collection->get('user.logout')) {
          $route->setDefaults([
            '_controller' => '\Drupal\my_custom\Controller\MyCustomUserLogoutController::logout',
          ]);
        }
      }

    }

Then add entry into my_custom.services.yml:

  my_custom.route_subscriber:
    class: Drupal\my_custom\EventSubscriber\MyCustomRouteSubscriber
    tags:
      - { name: event_subscriber }

Then create actual controller which will replace users module logout method. my_custom/src/Controller/MyCustomUserLogoutController.php

<?php

namespace Drupal\my_custom\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Routing\TrustedRedirectResponse;

/**
 * Class MyCustomUserLogoutController.
 */
class MyCustomUserLogoutController extends ControllerBase {

  /**
   * Logs the current user out.
   *
   * @return \Symfony\Component\HttpFoundation\RedirectResponse
   *   A redirection to home page.
   */
  public function logout() {
    user_logout();
    $logout_url = 'https://google.com'
    return new TrustedRedirectResponse($logout_url);
  }

}

Hope it will save your time.

Thanks

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.