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. Getting the User ID is way harder than it ever should be to be perfectly honest.

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. There is absolutely no method named this other than in the user Entity, if your entity contains a column named id.

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. Be careful what you you choose when your IDE suggests a list. You want this Security

use Symfony\Component\Security\Core\Security;

Then your ide wont show the getId() method, or will warn something about a polymorphic call blah blah.  But  there is a getId() method of the user Entity 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. I wish there was more info about this since this is one of the most popular articles on this site


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

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