phpsymfonylogout

Symfony: how to display a success message after logout


In Symfony, after a user successfully log out, how to display a success message like "you have successfully logged out" ?


Solution

  • 1) Create a new service to handle the logout success event.

    In services.yml add the service:

    logout_success_handler:
        class: Path\To\YourBundle\Services\LogoutSuccessHandler
        arguments: ['@security.http_utils']
    

    And add the class, replacing /path/to/your/login with the url of your login page (in the last line of the controller):

    <?php
    
    namespace Path\To\YourBundle\Services;
    
    use Symfony\Component\HttpFoundation\Request;
    use Symfony\Component\Security\Http\HttpUtils;
    use Symfony\Component\Security\Http\Logout\LogoutSuccessHandlerInterface;
    
    class LogoutSuccessHandler implements LogoutSuccessHandlerInterface
    {
        protected $httpUtils;
        protected $targetUrl;
    
        /**
         * @param HttpUtils $httpUtils
         */
        public function __construct(HttpUtils $httpUtils)
        {
            $this->httpUtils = $httpUtils;
    
            $this->targetUrl = '/path/to/your/login?logout=success';
        }
    
        /**
         * {@inheritdoc}
         */
        public function onLogoutSuccess(Request $request)
        {
            $response = $this->httpUtils->createRedirectResponse($request, $this->targetUrl);
    
            return $response;
        }
    }
    

    2) Configure your security.yml to use the custom LogoutSuccessHandler just created:

    firewalls:
        # ...
        your_firewall:
            # ...
            logout:
                # ...
                success_handler: logout_success_handler
    

    3) In the twig template of your login page add:

    {% if app.request.get('logout') == "success" %}
        <p>You have successfully logged out!</p>
    {% endif %}