How do I get the entity that represents the current user in Symfony?

Symfony 4+, 2019+ Approach

In symfony 4 (probably 3.3 also, but only real-tested in 4) you can inject the Security service via auto-wiring in the controller like this:


use Symfony\Component\Security\Core\Security;

class SomeClass
     * @var Security
    private $security;

    public function __construct(Security $security)
       $this->security = $security;

    public function privatePage() : Response
        $user = $this->security->getUser(); // null or UserInterface, if logged in
        // ... do whatever you want with $user

Symfony 2- Approach

As @ktolis says, you first have to configure your /app/config/security.yml.

Then with

$user = $this->get('security.token_storage')->getToken()->getUser();

should be enougth!

$user is your User Object! You don’t need to query it again.

Find out the way to set up your providers in security.yml from Sf2 Documentation and try again.

Best luck!

Leave a Comment