Use Eloquent Relationships. Read more about it in Laravel docs.
That is the solution you are looking for.
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I have a couple of models that have similar relations to a third model. I'd like to reduce database queries by either caching the query result or reusing one result to populate relations.
This is how my models are set up:
public class A{
public function relatedC(){
return $this->belongsTo(C::class);
}
}
public class B{
public function relatedC(){
return $this->belongsTo(C::class);
}
}
public class C{
public function relatedAs(){
return $this->hasMany(A::class);
}
public function relatedBs(){
return $this->hasMany(B::class);
}
}
Ideally I'd like to do something like this with only one database query, using the results I got from the get all to populate the relations:
$all_c = C::all();
$all_a = A::with('relatedC')->get();
$all_b = B:with('relatedC')->get();
Is there any built-in functionality to do this or do I have to implement it myself?
Please or to participate in this conversation.