I'm using the security bundle for Symfony 4.4.
My "User" entity is related to the "Info" entity on OneToOne.
When I'm logged I want to have "Info" data without extra query.
for exemple in my controller (after login)
when I use $this->getUser();
I have
App\Entity\User\User {#1705 ▼
-id: 1
-email: "[email protected]"
-roles: array:1 [▶]
-password: "password"
-info: Proxies\__CG__\App\Entity\User\Info {#1716 ▼
+__isInitialized__: false
-id: 1
-firstname: null
-lastname: null
}
}
Expected result
App\Entity\User\User {#1705 ▼
-id: 1
-email: "[email protected]"
-roles: array:1 [▶]
-password: "password"
-info: Proxies\__CG__\App\Entity\User\Info {#1716 ▼
+__isInitialized__: true
-id: 1
-firstname: "Firstname"
-lastname: "Lastname"
}
}
In my guard
in getUser
method of my guard I'm using UserRepository
for find my user by email.
// \App\Security\AppCustomAuthenticator
public function getUser($credentials, UserProviderInterface $userProvider)
{
// Load / create our user however you need.
// You can do this by calling the user provider, or with custom logic here.
$user = $this->userRepository->findUserByEmail($credentials['email']);
if (!$user) {
// fail authentication with a custom error
throw new CustomUserMessageAuthenticationException('User not found');
}
return $user;
}
// \App\Repository\User\UserRepository
public function findUserByEmail(string $email): ?User
{
return $this->createQueryBuilder('user')
->addSelect('user_info')
->leftJoin('user.info', 'user_info')
->andWhere('user.email = :email')
->setParameter('email', $email)
->getQuery()
->getOneOrNullResult()
;
}
but I'm loosing the entity Info
data after my login.
How to keep my relation entity data after login ?
It's a very good question I find because it's really often met by beginners. The link between a custom provider and the getUser() method is not always obvious.
Often the user is not alone in an application, he comes with an address, a team, a size, a color, a packet of information that it is useful to have on hand everywhere without making additional requests.
This link is for Symfony 4.x https://symfony.com/doc/4.0/security/custom_provider.html
This link can be usefull for Synfony 5.x
https://symfony.com/doc/current/security/user_provider.html#using-a-custom-query-to-load-the-user