Symfony FosUserBundle shows only user with role == ROLE_USER

I am trying to get only user with ROLE_USER .

I have this in the 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 only need to show User.getRoles()== "ROLE_USER" .

+7
orm symfony doctrine fosuserbundle
source share
3 answers

I found a 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 helps.

+4
source share

Your problem is that the User model in FOSUserBundle never has 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 , add ROLE_USER by default, and when you addRole , check if the role is ROLE_USER , and then skip if that happens.

In fact, each user of your system will have ROLE_USER to find all users with a role that you can simply do SELECT u FROM StageUserBundle:User u .

+5
source share

I am not an SQL guru, but I think this case is difficult because the roles field is a json type

You can try this

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

It will look for roles that contains "ROLE_USER" , not ADMIN

0
source share

All Articles