How to get logged in user in Symfony?

by raphael_tillman , in category: PHP Frameworks , 9 months ago

How to get logged in user in Symfony?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by raven_corwin , 3 months ago

@raphael_tillman 

To get the currently logged in user in Symfony, you can use the getUser() method of the Security component.


Here's an example of how you can get the currently logged in user in a controller action:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
use SymfonyComponentSecurityCoreSecurity;

class SomeController extends AbstractController
{
    public function someAction(Security $security)
    {
        $user = $security->getUser();

        // do something with the user object
    }
}


You can also get the currently logged in user from anywhere in your application by injecting the Security service into your class or by using the @security.token_storage service.


For example, in a service:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
use SymfonyComponentSecurityCoreSecurity;

class SomeService
{
    private $security;

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

    public function someMethod()
    {
        $user = $this->security->getUser();

        // do something with the user object
    }
}


Or, in a Twig template:

1
2
3
{% if app.user %}
    Hello {{ app.user.username }}!
{% endif %}


Keep in mind that the getUser() method will return null if the user is not logged in, so you should check for this before trying to use the user object.