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

Benko's avatar
Level 6

Eloquent query with 3 tables

I have 3 tables: exercises, sets and set_exercise. exercises and sets provide the simple lists of sets/tables. set_exercise defines which exercises belong to which sets (using ids, so set_id and exercise_id).

In this table also, each row contains some additional data for a given row. How do I get the list of all exercises with this additional data the best way (ideally using a single Eloquent query(?

0 likes
2 replies
JohnBraun's avatar
Level 33

Hi @benko ,

Is it correct that you are asking how to obtain the extra columns as defined in the set_exercise pivot table?

If so, you'll first need to load them in your Exercise and/or Set model as follows:

// Set.php (model)

public function exercises()
{
  return $this->belongsToMany(Exercise::class)->withPivot('extra_column1', 'extra_column2');
}

Now you can retrieve them, when you collect the exercises in a set:

foreach ($set->exercises() as $exercise) {
  echo $exercise->extra_column1;
}

This is a tweaked example from the documentation (https://laravel.com/docs/5.8/eloquent-relationships#many-to-many)

1 like
Benko's avatar
Level 6

Yes, exactly. Thank you. :)

Please or to participate in this conversation.