This package can handle relations through multiple tables (table 1 through table 2 through table 3 etc...): https://github.com/staudenmeir/eloquent-has-many-deep
Oct 21, 2025
5
Level 2
What is the best way to retrieve data from related tables?
Hello everyone. I have three tables that are related. In the handlers, given the record ID of the first table, I need to get an array of values from the third table with certain parameters. Can you tell me the best way to do this? I did it this way, but maybe it's not quite right and there's a better way.
// model 1 table
public function relation_1()
{
return $this->hasMany(TwoTable::class, 'two_id', 'id')
->with(['relation_2' => function ($query) {
$query->select('id', 'three_id')->where('status', 1);
}]);
}
// controller
...
$result = OneTable::with('relation_1')->find($id);
$collect_res = [];
if($result){
foreach ($result->relation_1 as $val) {
foreach ($val->relation_2 as $val_2) {
$collect_res[] = $val_2->id;
}
}
}
dd($collect_res);
Please or to participate in this conversation.