How to get logged in user in Symfony?

by raphael_tillman , in category: PHP Frameworks , 2 years ago

How to get logged in user in Symfony?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by raven_corwin , a year 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.

by hal.littel , 8 months ago

@raphael_tillman 

You can get the currently logged in user in Symfony by using the Security component.

  1. Inject the SymfonyComponentSecurityCoreSecurity class in your controller or service:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
use SymfonyComponentSecurityCoreSecurity;

class YourController
{
    private $security;
    
    public function __construct(Security $security)
    {
        $this->security = $security;
    }
    
    // ...
}


  1. Use the getUser() method of the Security class to get the currently logged in user:
1
$user = $this->security->getUser();


The getUser() method returns the authenticated UserInterface object representing the logged in user. You can then access the user's properties and methods as needed.


Note that the getUser() method also returns null if there is no authenticated user. Therefore, you should add appropriate checks to ensure that the user is logged in before trying to access their information.