I have two models with a very simple hasMany relationship:
// Location.php
public function forecasts()
{
return $this->hasMany('App\Forecast');
}
// Forecast.php
public function location()
{
return $this->belongsTo('App\Location');
}
Following the Laravel documentation on constraining eager loads, I want to get all Locations along with the latest Forecast belonging to that location, but I can't use the limit() method:
// LocationsApiController.php
public function index()
{
$locations = Location::with(['forecasts' => function ($query) {
$query->latest()->limit(1); // LIMIT NOT ALLOWED
}])->get();
return response($locations->jsonSerialize(), Response::HTTP_OK);
}
How do I build a query to get latest forecast for each location?
EDIT: It's possible to define a separate hasOne Eloquent relation between Location and Forecast (e.g. latestForecast) and doing the limit there. (That Staudenmeir package looks very interesting too!) However, this relationship would produce a "nonstandard" output in the JSON (ideally the JSON returned would be exactly the same structure as Location::with('forecasts')->get();, just with only one object in the forecasts array instead of multiple). This allows the Vue components on the frontend to be highly reusable and not worry about what context they are being used in, they just render the data.