Search code examples
phpsymfonysymfony-security

Symfony error on login page on implement UserLoaderInterface


I am using symfony version 5.4.4., and the first page of my application is a login page, but when I load it, I get this error:

You must either make the "App\Entity\mUser" entity Doctrine Repository ("App\Repository\mUserRepository") implement "Symfony\Bridge\Doctrine\Security\User\UserLoaderInterface" or set the "property" option in the corresponding entity provider configuration.]

Whats causing this error?


Solution

  • Symfony does not know how to get the users from the Doctrine repository.

    The error is pretty explicit about what you need to do.

    You have two options:

    Either you change your existing user repository (App\Repository\mUserRepository) so it implements the Symfony\Bridge\Doctrine\Security\User\UserLoaderInterface

    The interface has only one method:

    public function loadUserByUsername(string $username);
    

    So you'd need to do something like:

    class App\Repository\mUserRepository implements UserLoaderInterface
    {
        public function loadUserByUsername(string $username): ?UserInterface
        {
           // implement logic to get user from the repository by its username.
        }
    }
    

    Note that if you check that interface, the method loadUserByUsername() is actually deprecated, and has been replaced by loadUserByIdentifier() in Symfony 6+. To future-proof your implementation you should have something like:

    class App\Repository\mUserRepository implements UserLoaderInterface
    {
        public function loadUserByUsername(string $username): ?UserInterface
        {
           return $this->loadUserByIdentifier($username);
        }
    
        public function loadUserByIdentifier(string $identifier): ?UserInterface
        {
           // implement logic to get user from the repository by its username.
        }
    }
    

    Alternatively, the error message is telling you to just configure which property you use as identifier for your users.

    Let's say that you get them by email, and there is an mUser::email property.

    providers:
            mUserProvider:
                entity:
                    class: App\Entity\mUser
                    property: email