getting current logged in user - symfony 4
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
Alexander Br.
Updated on June 04, 2022Comments
-
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 over 5 yearsIn what context are you trying to get the current user - is this on the controller layer or the service layer?
-
Alexander Br. over 5 yearsin this controller which extends AbstractController
-
Cerad over 5 yearsIn general. when using the Doctrine ORM you will never access or use the id. Might need to review the basics.
-
Alexander Br. over 5 yearslet's say i want to post a comment by current authenticated user :). how ?
-
-
Alexander Br. over 5 yearsi 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 over 5 yearsSo 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 theUserInterface
injection, I had to get the username with$user->getUsername()
and then perform a look up on theUserRepository
myself. Are either of these options working for you? Is the user actually being logged in? -
Martin Dimitrov over 4 yearsI couldn't inject
UserInterface
but was able to do so withTokenStorageInterface
. Calling$this->tokenStorage->getToken()->getUser()
retrieves the currently logged in user.