getting current logged in user - symfony 4
Clash Royale CLAN TAG#URR8PPP
getting current logged in user - symfony 4
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 :)
in this controller which extends AbstractController
– Alexander Br.
Aug 12 at 6:52
In general. when using the Doctrine ORM you will never access or use the id. Might need to review the basics.
– Cerad
Aug 12 at 13:54
let's say i want to post a comment by current authenticated user :). how ?
– Alexander Br.
Aug 28 at 15:27
1 Answer
1
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
.
$this->getUser()
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.
UserInterface
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
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
– Alexander Br.
Aug 12 at 7:18
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?– Jason Ilicic
Aug 12 at 7:24
$this->getUser()->getId()
UserInterface
$user->getUsername()
UserRepository
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
In what context are you trying to get the current user - is this on the controller layer or the service layer?
– Jason Ilicic
Aug 12 at 6:48