laravel query child relation
// laravel query child relation
// Parent Model
class Group extends Model
{
public function group_members()
{
return $this->hasMany(GroupMember::class);
}
}
// Child Model
class GroupMember extends Model
{
public function group()
{
return $this->belongsTo(Group::class, 'group_id');
}
}
// Getting All groups where logged in user belong to
$loggedin_user_id = Auth::user()->id;
$groups = Group::with('group_members')->whereHas('group_members', function ($q) use($loggedin_user_id) {
$q->where('user_id', '=', $loggedin_user_id);
})->get();