Q: Orderby a field from relation table in Laravel I have events in my projects, and each event can have multiple dates, e.g event "XYZ" can be on "21st Jan", "20 August", and "30 December", and they are yearly recursive. Here are my models:
class Event extends Model {

    public function dates() {
        return $this->hasMany('App\EventDate');
    }

}


class EventDate extends Model
{

    public function event()
    {
        return $this->belongsTo('App\Event');
    }
}

Now I want to select events and order them by event date is nearer in future.
Event::with(['dates'=>function($query) {
$query->where('start_date', '>', Carbon::now());
  $query->orderBy('start_date');
}]);
But its recursive every year, so to check for future events that is an issue here, as well as ordering the events itself on its start_date.

A: The easiest option would be to fetch event dates and their corresponding events:
$eventDates = EventDate::with('event')
  ->where('start_date', '>', Carbon::now())
  ->orderBy('start_date')
  ->all();

Now you can iterate through the event dates and access event data the following way:
foreach ($eventDates as $eventDate) {
  echo $eventDate->event->name;
}

