Ad

Retrieving All Users From Group [laravel]

- 1 answer

I have 3 groups and 16 users belonging to these groups randomly. I am using

$groups = \App\Group::with('users')->get();

operand to get groups and users. But i only have 1 group filled with users, others group (which is linked in intermediate table) are empty.

In Group model i have these:

class Group extends Model
{
protected $table = 'crm_groups';
protected $primaryKey = 'group_id';
protected $fillable = ['name'];
public $timestamps = true;

public function users()
{
    return $this->belongsToMany('\App\User', 'crm_user_groups', 'user_id', 'group_id');
}

}

Database:

 INSERT INTO `crm_user_groups` (`id`, `group_id`, `user_id`) VALUES
 (1,    1,  1),
 (2,    2,  1),
 (3,    2,  1),
 (4,    3,  1),
 (5,    2,  14),
 (6,    2,  15),
 (7,    3,  16);
Ad

Answer

You've passed the wrong place of your param.

public function users()
{
    return $this->belongsToMany('\App\User', 'crm_user_groups','group_id', 'user_id');
}

If you're accessing it from Group model then the first param should be 'group_id' and then 'user_id'.

The third argument is the foreign key name of the model on which you are defining the relationship, while the fourth argument is the foreign key name of the model that you are joining to.

Ad
source: stackoverflow.com
Ad