Skip to content
Advertisement

Sort By date in hasMany relation first record for Laravel project [closed]

I have a courses table and every course has many sessions,

So I need to sort courses by the first session of the course date for Laravel Project.

Advertisement

Answer

this way you can set a method in Course model to get the oldest Session model(which means first session):

public function oldestSession()
{
   return $this->hasOne(Session::class)->oldestOfMany();
}

and then you may simply query your course model by adding constraints on that method :

$courses = Course::with(['oldestSession' => function ($query) {
    $query->orderBy('created_at', 'desc');
}])->get();
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement