How to add a role to an user with FOSUserBundle in Symfony 3

An user role is a predefined role that allow the users to execute different activities in your application. There are a lot of points to handle when you work with user permissions (not mentioned here), in order to make that easier for the user and for the developer, the implementation of Roles is an useful (and basically required) feature of an User system.

In this article, you'll learn how to add roles to an user using FOSUserBundle in Symfony 3.

With Doctrine

You can add a role to an user using the addRole method of the user object.

<?php

namespace ourcodeworld\adminBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class AdminController extends Controller
{
    public function indexAction()
    {
        // Retrieve entity manager of doctrine
        $em = $this->getDoctrine()->getManager();

        // Search for the UserEntity, retrieve the repository
        $userRepository = $em->getRepository("myBundle\Entity\User");
        // or $userRepository = $em->getRepository("myBundle:User");

        $user = $userRepository->findOneBy(["username" => "AnyUsername"]);
        
        // Add the role that you want !
        $user->addRole("ROLE_ADMIN");

        // Save changes in the database
        $em->persist($user);
        $em->flush();
    }
}    

With fos_user.user_manager

You can create an user using the fos user manager, service that can be retrieved from the container ($this->get('serviceName') in a controller or $container->get('') in any other place with the container in context).

<?php

namespace ourcodeworld\adminBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class AdminController extends Controller
{
    public function indexAction()
    {
        $userManager = $this->get('fos_user.user_manager');

        // Use findUserby, findUserByUsername() findUserByEmail() findUserByUsernameOrEmail, findUserByConfirmationToken($token) or findUsers()
        $user = $userManager->findUserBy(['id' => 1]);
        
        // Add the role that you want !
        $user->addRole("ROLE_ADMIN");
        // Update user roles
        $userManager->updateUser($user);
    }
}

In the user class

You can also set the role in the constructor of the User Entity class everytime an user is registered:

<?php
// src/Acme/UserBundle/Entity/User.php

namespace myBundle\Entity;

use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="fos_user")
 */
class User extends BaseUser
{
    public function __construct()
    {
        parent::__construct();
        
        // Add role
        $this->addRole("ROLE_ADMIN");
    }
}

The context of $this will be specifically the BaseUser.

With FOSUserBundle Command Line Tools

By default, a symfony application that implements FOSUserBundle, will automatically have access to the Command line tools of this bundle. This tools provide an useful command that allow you to add a role to an user, the fos:user:promote command. This command enables you to add a role to a user or make the user a super administrator:

php bin/console fos:user:promote username ROLE_ADMIN

Have fun !

Become a more social person