How to Get The Current User in Controller in Symfony 6

1 year ago admin Symfony

In today's lesson, we are going to see how to get the current Logged in user in Symfony 6, it is useful when trying to check if the user is authenticated before accessing a method in your controller.


Get the current logged in user in Symfony 6

So to get the current Logged in user in Symfony 6 you can do it like this: 

                                                    
                                                                                                                
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class ProfileController extends AbstractController
{
    public function index(): Response
    {
 
        // check if the user is authenticated first
        $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');

        //return the current logged in user
        /** @var \App\Entity\User $user */
        $user = $this->getUser();

        //redirect the user or display a message
        return new Response('Well hi there '.$user->getFirstName());
    }
}