getting current logged in user - symfony 4

13,262

In a Symfony 4 controller, you should be able to access the user using $this->getUser() within a controller providing that the user is authorized. If there is no logged in user, it should return null.

public function agencyHome(EntityManagerInterface $em)
{
    $this->denyAccessUnlessGranted('ROLE_USER');
    $user = $this->getUser();
}

Alternatively, you should also be able to inject the UserInterface class into the method parameters through which you can get information about the current logged in user.

public function agencyHome(EntityManagerInterface $em, UserInterface $user)
{
   ...
}

I've tested these on a Symfony 4 application, though I can't remember if I had to do anything else in the configuration so please let me know if you have any issues with them.

Referenced from https://symfony.com/doc/current/security.html

Share:
13,262
Alexander Br.
Author by

Alexander Br.

Updated on June 04, 2022

Comments

  • Alexander Br.
    Alexander Br. almost 2 years
    public function agencyHome(EntityManagerInterface $em)
    {
        $repository = $em->getRepository(Ships::class);
        // $ships = $repository->findByOwner($own);
        $ships = $repository->findAll();
        return $this->render('agency/index.html.twig', [
            'ships' => $ships,
        ]);
    }
    

    on the code above i need to pass current logged in user to a repository, so i can find all related "ships" i tried with $u = $this->getUser()->getId(); with no succes :(

    thank you in advance :)

    • jaseeey
      jaseeey over 5 years
      In what context are you trying to get the current user - is this on the controller layer or the service layer?
    • Alexander Br.
      Alexander Br. over 5 years
      in this controller which extends AbstractController
    • Cerad
      Cerad over 5 years
      In general. when using the Doctrine ORM you will never access or use the id. Might need to review the basics.
    • Alexander Br.
      Alexander Br. over 5 years
      let's say i want to post a comment by current authenticated user :). how ?
  • Alexander Br.
    Alexander Br. over 5 years
    i know that very well, however, how do i get the ID of the user so i can pass it to a repository, to select some items related to the current user
  • jaseeey
    jaseeey over 5 years
    So from my test on my application, I was able to call $this->getUser()->getId() as per your original attempt and it returned me with the user ID. Alternatively, with using the UserInterface injection, I had to get the username with $user->getUsername() and then perform a look up on the UserRepository myself. Are either of these options working for you? Is the user actually being logged in?
  • Martin Dimitrov
    Martin Dimitrov over 4 years
    I couldn't inject UserInterface but was able to do so with TokenStorageInterface. Calling $this->tokenStorage->getToken()->getUser() retrieves the currently logged in user.