How to make username email case insensitive in symfony?

by dalton_moen , in category: PHP Frameworks , 9 months ago

How to make username email case insensitive in symfony?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by daisha , 9 months ago

@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. Create a new Event Listener class. Run the following command to generate the class file:
1
php bin/console make:listener CaseInsensitiveUsernameListener


  1. Open the generated CaseInsensitiveUsernameListener.php file and update its contents as follows:
 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. Register the listener as a service in config/services.yaml. Open the file and add the following code:
1
2
3
4
services:
    AppEventListenerCaseInsensitiveUsernameListener:
        tags:
            - { name: doctrine.event_listener, event: prePersist }


  1. Save the changes and clear the cache by running the following command:
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.