简体   繁体   中英

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 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM