2
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 :)

cybernet2u
  • 146
  • 1
  • 3
  • 14
  • 1
    In what context are you trying to get the current user - is this on the controller layer or the service layer? – jaseeey Aug 12 '18 at 06:48
  • in this controller which extends AbstractController – cybernet2u Aug 12 '18 at 06: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 '18 at 13:54
  • let's say i want to post a comment by current authenticated user :). how ? – cybernet2u Aug 28 '18 at 15:27
  • Does this answer your question? [How to get the current logged User in a service](https://stackoverflow.com/questions/36870272/how-to-get-the-current-logged-user-in-a-service) – Nico Haase Dec 09 '22 at 15:41

1 Answers1

5

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

jaseeey
  • 281
  • 4
  • 15
  • 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 – cybernet2u Aug 12 '18 at 07:18
  • 1
    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? – jaseeey Aug 12 '18 at 07:24
  • 2
    I couldn't inject `UserInterface` but was able to do so with `TokenStorageInterface`. Calling `$this->tokenStorage->getToken()->getUser()` retrieves the currently logged in user. – Martin Dimitrov Sep 18 '19 at 18:55