Web Development

How to get the user id in a service in Symfony 5

I’m no Symfony expert, I write what I find as I find it. Nothing in the documentation really covers this subject, so I am not sure what the correct way is of if there even is one.

There are a few ways I have found to get a user id. None of the classes you can inject such as UserInterface, SessionInterface, TokenInterface, Security etc. contain an actual getUserId() method.

You can  get a user object from the Security class, as seen in the documentation here. To do so you type hint aka Dependency Inject your service constructor with Security but not just any Security will do there is also one by Sensio labs and another. You want this Security

use Symfony\Component\Security\Core\Security;

Then your ide wont show it or will warn something about a polymorphic call blah blah, but apparently there is a getId() method of the user returned from Security and you can get a user id like this.

/** @var User $user */
$user = $this->security->getUser()->getId();
$userId = $user->getId();

This method may return null if the user is not logged in so you need to check for that. The @var syntax tells the IDE what is going on so it knows there is a getId() method, you will also need to import that class. The User object it refers to is your App/Entity/User class.

Forgive me if anything is wrong.
Link to a Symfony cast with a little more info but not much.

3 replies on “How to get the user id in a service in Symfony 5”

> You might try UserInterface but I know that Security will work

that sentence makes no sense

> you can get a user id like this.
> $userId = $this->security->getUser()->getId();

`getUser` can return `null` for not authenticated user

> My IDE PHPStorm doesn’t even know getId() exists so I had to do some digging.

because `Security::getUser()` returns `Symfony\Component\Security\Core\User\UserInterface` and this interface does not have `getId()` method. Users in your app may not have id, that’s totally implementation dependent

Leave a Reply to smartass Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.