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

skonsoft picture skonsoft · Sep 29, 2012 · Viewed 68k times · Source

I'm using FOSUserBundle to authenticate my users.

I'm trying to get the user object inside the Controller to register a trip where I should add the user object to this Trip before save.

I did not found how to do that because next method where I found it in symfony doc:

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

renders the username as string, but I need the whole object.

Currently, I use this method, but it's not working properly.

$username = $this->container->get('security.context')->getToken()->getUser();
$em = $this->container->get('doctrine')->getEntityManager();
$user = $em->getRepository('SiteUtilisateurBundle:Utilisateur')->find($username);

How can I correctly do this?

Answer

Mohammad Niknam picture Mohammad Niknam · Mar 6, 2013

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.