I am using the FOS bundle and I want to retrieve all users with a given ROLE from the database.
What is the best way to do this?
I am using the FOS bundle and I want to retrieve all users with a given ROLE from the database.
What is the best way to do this?
Just add this in your UserRepository or replace
$this->_entityName
byYourUserBundle:User
:If you are using FOSUser Groups you should use:
Finally i solved it, following is an exact solution:
Cheers!
In case you need to filter users by role using a DQL filter in a YAML file (In EasyAdminBundle for instance)
If you have this requirement and your user list will be extensive, you will have problems with performance. I think you should not store the roles in a field as a serialized array. You should create an entity roles and many to many relationship with the users table.
As @Tirithen states, the problem is that you will not get the users that have an implicit role due to role hierarchy. But there is a way to work around that!
The Symfony security component provides a service that gives us all child roles for a specific parent roles. We can create a service that does almost the same thing, only it gives us all parent roles for a given child role.
Create a new service:
Define your service for instance in yaml and inject the role hierarchy into it:
Now you are ready to use the class in your own service. By calling
$injectedService->getParentRoles(['ROLE_YOUR_ROLE']);
you will get an array containing all parent roles that will lead to the 'ROLE_YOUR_ROLE' permission. Query for users that have one or more of those roles... profit!For instance, when you use MongoDB you can add a method to your user document repository:
I'm not into Doctrine ORM but I'm sure it won't be so different.
You can use just this on your DQL:
Of course with QueryBuilder it's more elegant: