@dalton_moen
To make the username/email case insensitive in Symfony, you can use an event listener to convert the entered username/email to lowercase before persisting it to the database.
Here are the steps to achieve this:
1
|
php bin/console make:listener CaseInsensitiveUsernameListener |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<?php namespace AppEventListener; use DoctrineORMEventLifecycleEventArgs; use SymfonyComponentSecurityCoreUserUserInterface; class CaseInsensitiveUsernameListener { public function prePersist(LifecycleEventArgs $args) { $entity = $args->getObject(); if (!$entity instanceof UserInterface) { return; } $email = $entity->getEmail(); if ($email !== null) { $entity->setEmail(strtolower($email)); } } } |
1 2 3 4 |
services: AppEventListenerCaseInsensitiveUsernameListener: tags: - { name: doctrine.event_listener, event: prePersist } |
1
|
php bin/console cache:clear |
Now, whenever a user is created or updated, the CaseInsensitiveUsernameListener
will be triggered, converting the email to lowercase before persisting it to the database. This ensures case insensitivity when searching or authenticating users by their email addresses in Symfony.