Reputation: 4979
I am working on a project in which a user will have multiple roles. I am kind of clueless on how to tackle this situation. Currently , I have a users
table and a roles table
[
I have also created a pivot table user_roles
which adds roles for a user
I have added belongsToMany clause in the users table.
public function roles() {
//return $this->hasMany(EventUser::class);
return $this->belongsToMany(Role::class, 'portal_user_roles', 'user_id', 'role_id')->withTimestamps();
}
I need to fetch the users based on their role. The role id will be passed from the frontend.
Can you please suggest a way i can find the users matching a particular role?
Thanks.
Upvotes: 1
Views: 891
Reputation: 2844
For getting all users that have a role, first, define your relationships in your Models(Role & User):
Role Model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
public function user() {
return $this->hasMany(User::class, 'foreign_key', 'role_id');
}
}
?>
User Model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function role() {
return $this->belongsTo(Role::class);
}
}
?>
In your view just call the user method that you have created in your Role Model:
@if($roles)
@foreach($roles AS $role)
@if($role->user)
@foreach($role->user AS $user)
{{ $user->id.": ".$user->title }}
@endforeach
@endif
@endforeach
@endif
Upvotes: 0
Reputation: 446
first of all define a relation in your user model.
public function users() {
return $this->belongsToMany(User::class);
}
then in your controller you can write
$users = Role::findOrFail($request->role_id)->users;
done
Upvotes: 2
Reputation: 40730
If you don't want to define the relationship on the role direction and get the users that way (which you should it makes more sense I think) you can do this on the user's side:
$roleId = 15; // Or whatever
$usersWithRole15 = Users::whereHas('roles', function ($query) use ($roleId) {
$query->where('id', $roleId);
})->get();
Upvotes: 2
Reputation: 2987
In Role model you also need users()
relationship
// Role model
public function users()
{
return $this->belongsToMany(User::class, 'user_roles');
}
Then in your controller, when you have $roleId
, you can get the role and its users.
$role = Role::find($roleId);
$role->users;
PS. not sure about your pivot table name, you referred to as user_roles
but in your code it's portal_user_roles
Upvotes: 3