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

RodneyZ's avatar

Query to retrieve the latest entry in a history table per student in Laravel 5.2

Here is my table

https://static.spiceworks.com/shared/post/0024/8448/table.jpg

What I want to happen is to populate the latest grades ONLY in English for students who have one. It should show like this

{"date":"2017/7/13","student_id":2,"grade":"C"} {"date":"2017/7/1","student_id":3,"grade":"D"} {"date":"2017/4/1","student_id":5,"grade":"E"}

However, in the the code that I have, this is what I show

{"date":"2017/7/13","student_id":2,"grade":"C"} {"date":"2017/7/1","student_id":3,"grade":"D"} {"date":"2017/4/1","student_id":5,"grade":"E"} {"date":"2017/3/1","student_id":2,"grade":"A"} {"date":"2017/2/1","student_id":3,"grade":"A"}

Please help.

Here is my controller

public function index() { $englishgrades = StudentHistory::select('date', 'student_id', 'grade') ->where('subject', 'English') ->distinct('student_id') ->orderBy('date','desc') ->get('student_id');

return view('home', ['englishgrades' => $englishgrades]); }

And this is the blade view

Total of {{ $englishgrades->count() }}

@foreach ($englishgrades as $englishgrade ) {{ $englishgrade }} @endforeach

0 likes
1 reply

Please or to participate in this conversation.