laravel query child relation

Solutions on MaxInterview for laravel query child relation by the best coders in the world

showing results for - "laravel query child relation"
Hailee
16 Feb 2020
1// laravel query child relation
2// Parent Model
3class Group extends Model
4{
5     public function group_members()
6    {
7        return $this->hasMany(GroupMember::class);
8    }
9}
10
11// Child Model
12class GroupMember extends Model
13{
14   	public function group()
15    {
16        return $this->belongsTo(Group::class, 'group_id');
17    }
18}
19
20// Getting All groups where logged in user belong to
21  $loggedin_user_id = Auth::user()->id;
22  $groups = Group::with('group_members')->whereHas('group_members', function ($q) use($loggedin_user_id) {
23    $q->where('user_id', '=', $loggedin_user_id);
24  })->get();
25