1
votes

I have an app made in Laravel 5 using the entrust package:

https://github.com/Zizaco/entrust/tree/laravel-5

I have a query that already runs fine that gets paginated users that match a search string like so:

User::like($search)->skip($offset)->take($limit)->get()

With entrust I have a role called admin so how would I adapt this query so it only returns users that have the role admin. This didnt work:

User::like($search)->hasRole('admin)->skip($offset)->take($limit)->get()
2
If that's the exact code that didn't work, it has a syntax error.ceejayoz

2 Answers

2
votes

You could try something like this:

User::whereHas('roles', function($q) {

    $q->where('name', 'admin');

})->skip($offset)->take($limit)->get();

I don't think hasRole() can be used as a query scope but I could be wrong. I believe it's for single user checks like:

if (Auth::user()->hasRole('admin')) {

    // Logged in user has the admin role...
}
0
votes

I also have used entrust in my application (laravel 4.2) got the logic and rewrote it as it serves my need correctly. I changed the name Role to Group for better understanding.

But in your case;

Roles could have many users Roles could have many permissions

Users belongs to Roles

Then you could

$role = Role::where("name", "admin")->first();
$role->users()->get();

would give you all the users that belongs to admin role..

Not: This is for laravel 4.2.