Answers for "laravel query child relation"

PHP
0

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();
Posted by: Guest on June-28-2021

Code answers related to "laravel query child relation"

Browse Popular Code Answers by Language