Laravel get related models of related models
Solution 1
Load related models using load
method on the Collection:
return RepairRequests::find($id)->vehicle->requests->load('repairItems');
which is basically the same as:
$repairRequest = RepairRequests::with('vehicle.requests.repairItems')->find($id);
return $repairRequest->vehicle->requests;
Solution 2
I'd suggest eager loading everything.
return RepairRequests::with('vehicle.requests.repaireItems')->find($id);
Tom Macdonald
I am a Operations Research and software engineer. I did my MSc in Nantes, France, my internship in Vienna, Austria, and come from London, UK. I am freelancing in Vienna. Feel free to contact me! I do anything interesting that's solvable in software, but also websites.
Updated on June 14, 2022Comments
-
Tom Macdonald almost 2 years
I have a RepairRequest model, which is associated with a Vehicle.
class RepairRequest extends \Eloquent { public function vehicle() { return $this->belongsTo('Vehicle'); } } class Vehicle extends \Eloquent { public function requests() { return $this->hasMany('RepairRequest'); } }
I would like to get all RepairRequests for the vehicle associated with a given RepairRequest, so I do
return RepairRequests::find($id)->vehicle->requests;
This works fine.
However, RepairRequests have RepairItems:
// RepairRequest class public function repairItems() { return $this->hasMany('RepairItem', 'request_id'); } // RepairItem class public function request() { return $this->belongsTo('RepairRequest', 'request_id'); }
which I would like to return too, so I do
return RepairRequests::find($id)->vehicle->requests->with('repairItems');
but I get the following exception:
Call to undefined method Illuminate\Database\Eloquent\Collection::with()
How can I write this so that the returned json includes the RepairItems in the RepairRequest json?
-
Jarek Tkaczyk almost 10 yearsYour 2nd suggestion
vehicle->requests()->with('repairItems');
executes exactly the same query as eager loading, but it won't set the relation on thevehicle
itself, only return the relatedrequests
with eager loadedrepairItems
, so it's rather not an option. -
Tom Macdonald almost 10 yearsWell yes I could load everything, but then I would have to do json traversal on the client side. It seems unnecessary.
-
user1669496 almost 10 yearsTry
return RepairRequests::find($id)->vehicle->requests()->with('repairItems')->get();
. I originally had this as part of my answer but not realizing that it wasn't going to return the original vehicle information, it was removed. But if that's all you need, I'll add it again -
Jack Vial almost 8 yearsThey need to have this in the Laravel docs or at least have it explained more clearly if it is there. Thanks for the example.