Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Randy_Johnson's avatar

DB Eloquent Help

I have asked help earlier and got this

$this->attendances = Student::whereHas('attendance', function ($query) {
            $query->where('teacher_id', $this->teacherId);
        })->get();

Which is perfect but I also need the information from the attendance table which linked to the student.

mysql> select name, surname from students; +---------+---------+ | name | surname | +---------+---------+ | Johan | Reilly | | Burley | Toy | | Grant | Leannon | | Kaci | Brown | | Westley | Bayer | | Vernon | Little | | Ayden | Hintz | | Hillard | Kovacek | | Rupert | Dach | | Edmund | Pollich | +---------+---------+

+----+------------+------------+-----+---------+------+ | id | student_id | teacher_id | day | month | year | +----+------------+------------+-----+---------+------+ | 1 | 6 | 2 | 4 | January | 2021 | | 2 | 5 | 5 | 4 | January | 2021 | | 3 | 9 | 7 | 3 | January | 2021 | | 4 | 7 | 2 | 7 | January | 2021 | | 5 | 2 | 6 | 7 | January | 2021 | | 6 | 8 | 1 | 6 | January | 2021 | | 7 | 5 | 2 | 8 | January | 2021 | | 8 | 8 | 7 | 7 | January | 2021 | | 9 | 4 | 8 | 1 | January | 2021 | | 10 | 4 | 9 | 4 | January | 2021 | +----+------------+------------+-----+---------+------+

Basically, I need the student name, as well as the information from attendance of day and month.

I assumed I would use a join for such a thing, and that I have gone down the wrong route with where.

0 likes
2 replies
automica's avatar
automica
Best Answer
Level 54

you can access this information in the blade, if you follow the relationship from attendance to student

@foreach($attendances as @attendance)

{{ $attendance->student->name }}  {{ $attendance->student->surname }}   {{ $attendance->day }}   {{ $attendance->month }}  {{ $attendance->year }}  

@endforeach
Randy_Johnson's avatar

Dammit, I just spent the last four hours coming up with this.

        $data = Student::with('attendance')->whereHas('attendance', function ($query) {
            $query->where('teacher_id', $this->teacherId);
        })->get();

Please do you know any good tutorials on this stuff. This seems to be an area where I always get stuck.

Please or to participate in this conversation.