Laravel get related models of related models

Thursday, July 3, 2014

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?







http://ift.tt/1khOaJc