1

The user can log in, but i need his id to show his profile. Since i'm working in symfony 4, the many possible answers i've found were obsolete.

Liana.R
  • 124
  • 2
  • 10
  • Perhaps you can find your answer [here](https://stackoverflow.com/questions/25682743/how-to-set-session-variables-for-all-the-controllers-in-symfony2)? – Dennishofken Apr 26 '18 at 21:23
  • 1
    Why don't you try the answers before saying they are obsolete? `$this->getUser()` is valid wether you use symfony 2 or 4 – Liora Haydont Apr 26 '18 at 21:25
  • Possible duplicate of [Symfony2 getting logged in user's id](https://stackoverflow.com/questions/10537879/symfony2-getting-logged-in-users-id) – Philippe-B- Apr 27 '18 at 04:55

1 Answers1

4

https://symfony.com/doc/current/security.html#retrieving-the-user-object

After authentication, the User object of the current user can be accessed via the getUser() shortcut (which uses the security.token_storage service). From inside a controller, this will look like:

public function index()
{
    $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');

    $user = $this->getUser();
}

The user will be an object and the class of that object will depend on your user provider. But, you didn't tell us what user provider you are using, so I have no way of telling you, beyond this, how to get to the id itself.

One other way to get the user:

An alternative way to get the current user in a controller is to type-hint the controller argument with UserInterface (and default it to null if being logged-in is optional):

use Symfony\Component\Security\Core\User\UserInterface\UserInterface;

public function indexAction(UserInterface $user = null)
{
    // $user is null when not logged-in or anon.
}

This is only recommended for experienced developers who don't extend from the Symfony base controller and don't use the ControllerTrait either. Otherwise, it's recommended to keep using the getUser() shortcut.

dave
  • 62,300
  • 5
  • 72
  • 93