Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

cupcaved's avatar

Laravel complex query

I have a 5 tables and i want this to be in the form of eloquent. How do i combine all tables using the with(), or their are other ways to do this.

  • student
  • schedule
  • schedule_student student_id,schedule_id
  • activity schedule_id
  • scores student_id, activity_id,score

My all models.

//Activity
    public function schedule()
    {
        return $this->belongsTo(Schedule::class);
    }
    public function students()
    {
        return $this->belongsToMany(Student::class,'scores');
    }

//Student

    public function schedules()
    {
        return $this->belongsToMany(Schedule::class,'schedule_student');
    }
    public function activities()
    {
        return $this->belongsToMany(Activity::class,'scores');
    }

//Schedule
    public function activities()
    {
        return $this->hasmany(Activity::class);
    }
    public function students()
    {
        return $this->belongsToMany(Student::class,'schedule_student');
    }

//Student
    public function student()
    {
        return $this->belongsTo(Student::class);
    }
    public function activity()
    {
        return $this->belongsTo(Activity::class);
}

How do i combine all 4 tables(except schedule_student) so the json will look like from below:

schedule[] 
   =>activities[]
         =>students[]
               =>scores[]
0 likes
2 replies
cupcaved's avatar

I got the idea. It's working now.

Thank you Bro.

Please or to participate in this conversation.