Home > front end >  Symfony get current User entity in controller
Symfony get current User entity in controller

Time:11-25

I'm beginner in Symfony (6.1) and sometimes I need to get the current User in my controllers.

The way I use for the moment is :

$user = $userRepository->find($this->getUser()->getId());

But they are a better way ?

Because $this->getUser() give me the UserInterface and I need the User entity. screenshot example

Thanks to read me

CodePudding user response:

Using $this->getUser() will get you the current user (that implements UserInterface). The getUser() method lives in AbstractController.php that is part of the Symfony FrameworkBundle. You could extend this controller if you really want to change the getUser() method to not use the UserInterface, but I think it would be better to simply change the typehint of the function (setUser) you call (in your screenshot -please write this out next time-) to use the UserInterface. Something like this:

public function setUser(UserInterface $user) 
{
    //....
}

CodePudding user response:

You have many ways to get your current user, please try this one:

$creditCard= new creditCard();
$creditCard->setUser($this->getUser());

Or this one:

$creditCard= $this->get('security.token_storage')->getToken()->getUser();
  • Related