enter image description here

I'm trying to get All roles in a user group in eloquent style.

//this function is defined in the ModelUserGroup
public function roles(){
    return $this->hasMany(ModelGroupRole::class, 'group_id','id');

I'm trying to get all roles like this:


I also tried ->hasManyThrough but it is not working for me.

I need all roles data like id,name, etc. using with.

2 Answers

Jack On Best Solutions

Looks like you need a belongsToMany relationship.

In your UserGroup model.

public function roles()
    // Assuming your role model is named ModelRole...
    return $this->belongsToMany(ModelRole::class, 'group_role', 'group_id', 'role_id');

Now you can do the following:

$group = ModelUserGroup::with('roles')->first();

dd($group->roles); // will be a collection of ModelRole's

Answered on my phone so there may be syntax errors.

Kais Ben Daamech On

As stated here in the many to many section, you have got to define the relationships as the follwing:

in User_Group :

 public function roles(){
       return  $this->belongsToMany('App\Pathto\Role', 'group_role','group_id','role_id');

in Role:

 public function user_groups(){        
      return $this->belongsToMany('App\Pathto\UserGroup', 'group_role', 'role_id', 'group_id');

Edit: ModelUserGroup::with('roles')->get() should work just fine then. (of course, change pathto with your path to the models.)