Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony FosUserBundle show only user with role == ROLE_USER

I am trying to get only user with ROLE_USER.

I have this in my controller:

$query = $this->getDoctrine()->getEntityManager()
->createQuery(
        'SELECT u FROM StageUserBundle:User u WHERE u.roles LIKE :role'
)->setParameter('role', '%"ROLE_USER"%' 
);
$users = $query->getResult();

It worked with ROLE_ADMIN instead of ROLE_USER but I need to show only User.getRoles()== "ROLE_USER".

like image 351
meherzi.sahbi Avatar asked Aug 07 '14 16:08

meherzi.sahbi


2 Answers

Your problem is that the User model in FOSUserBundle never actually has the ROLE_USER.

FOS\UserBundle\Model\UserInterface

const ROLE_DEFAULT = 'ROLE_USER';

FOS\UserBundle\Model\User

public function addRole($role)
{
    $role = strtoupper($role);
    if ($role === static::ROLE_DEFAULT) {
        return $this;
    }

    if (!in_array($role, $this->roles, true)) {
        $this->roles[] = $role;
    }

    return $this;
}

....

public function getRoles()
{
    $roles = $this->roles;

    foreach ($this->getGroups() as $group) {
        $roles = array_merge($roles, $group->getRoles());
    }

    // we need to make sure to have at least one role
    $roles[] = static::ROLE_DEFAULT;

    return array_unique($roles);
}

When you getRoles it add the ROLE_USER as a default and when you addRole it check to see if the role is ROLE_USER and then skips if it does.

In reality every user on your system will have the ROLE_USER so to find all users with the role you can just do a SELECT u FROM StageUserBundle:User u.

like image 101
qooplmao Avatar answered Nov 05 '22 01:11

qooplmao


I Found the solution to my problem . i changed this in my controller :

$query = $this->getDoctrine()->getEntityManager()
    ->createQuery('SELECT u FROM StageUserBundle:User u WHERE NOT u.roles LIKE :role'
    )->setParameter('role', '%"ROLE_ADMIN"%' );

    $users = $query->getResult();

Hope this will help.

like image 4
meherzi.sahbi Avatar answered Nov 04 '22 23:11

meherzi.sahbi