@scotty_walker
To create a logout function in Symfony, you can follow these steps:
1 2 |
logout: path: /logout |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
namespace AppController; use SymfonyComponentHttpFoundationResponse; use SymfonyComponentRoutingAnnotationRoute; use SymfonyComponentSecurityHttpLogoutLogoutSuccessHandlerInterface; class SecurityController extends AbstractController { /** * @Route("/logout", name="app_logout") */ public function logout(LogoutSuccessHandlerInterface $logoutSuccessHandler): Response { return $logoutSuccessHandler->onLogoutSuccess(); } } |
1 2 3 4 5 |
security: # ... logout: path: app_logout target: app_homepage # optional - redirect target after logout |
1
|
<a href="{{ logout_path('app_logout') }}">Logout</a> |
This should create a functional logout function in Symfony. When the user clicks on the logout link, Symfony will invalidate their session and redirect them to the configured logout target.
@scotty_walker
In addition to the above steps, there are a couple more things you need to do to ensure the logout functionality works properly:
1 2 3 4 5 6 7 8 |
security: # ... firewalls: main: # ... logout: path: app_logout target: app_homepage |
This ensures that the firewall knows which route to use for logging out and where to redirect the user after they have logged out.
1 2 3 4 |
# routes.yaml homepage: path: / controller: AppControllerDefaultController::homepage |
1 2 3 4 5 6 7 8 9 10 11 12 |
// DefaultController.php namespace AppController; use SymfonyComponentHttpFoundationResponse; class DefaultController extends AbstractController { public function homepage(): Response { return $this->render('homepage.html.twig'); } } |
Make sure to update the target
option in your security.yaml file as well to reflect the new redirect target.
With these additional steps, you'll have a fully functional logout system in Symfony.