5 months ago

Can you use an Aggregate on a Nested Eager Load?

Posted 5 months ago by ctyler

Hello all, So i have a database that contains courses. Each course has one attendance. Each attendance can have multiple Sessions. The course table has the start_date column. The end date for the course is the last session. I am currently using a sub query for this:

$end_date = DB::table('attendances')
            ->select('attendances.course_id', DB::raw('MAX(attendancesessions.session_date) as end_date'))
            ->leftjoin('attendancesessions', 'attendances.id', '=', 'attendancesessions.attendance_id')

$courses = $course
            ->JoinSub($end_date, 'end_date', function ($join) {
                $join->on('id', '=', 'end_date.course_id');
            ->when($cat, function ($query, $cat){
                return $query->where('course_cat_id', $cat);
            ->when($from, function ($query, $from) {
                return $query->where('start_date', '>=', $from); //2020-02-01
            ->when($to, function ($query, $to) {
                return $query->where('start_date', '<=', $to); //2020-02-29
            ->sortable(['start_date' => 'desc'])

This works okay but I was wondering if I could use an Aggregate on a Nested Eager Load some how.

$cousres = Course::with('attendance.attendancesessions')
        foreach($cousres as $course) {

This works but I need to use last() with a column session_date. When I try to pass session_date via:


I get an error: Argument 1 passed to Illuminate\Support\Collection::last() must be callable or null, string given, called in /var/www/html/dev-cls-training-com/app/Http/Controllers/Admin/CourseController.php on line 71

Please sign in or create an account to participate in this conversation.