Symfony2: How to get user Object inside controller when using FOSUserBundle? Symfony2: How to get user Object inside controller when using FOSUserBundle? symfony symfony

Symfony2: How to get user Object inside controller when using FOSUserBundle?


I think Ramon is right. You already have the user object.

Also in Symfony > 2.1.x you can use

$this->getUser();

inside the controller.


The documentation for the getUser method indicates:

either returns an object which implements __toString(), or a primitive string is returned.

And if we look in the FOS\UserBundle\Model\User class over here (the base user class used by the FOSUserBundle) we can see that it does indeed have a __toString method:

public function __toString(){    return (string) $this->getUsername();}

I think that you actually get the User object but because it implements a __toString method it can be rendered directly in templates.

In Twig you can use:

{{ dump(user) }}

To see what kind of object you have. But You are actually using an object, not a string.


Solution:

$userManager = $this->container->get('fos_user.user_manager');$user = $userManager->findUserByUsername($this->container->get('security.context')                    ->getToken()                    ->getUser())