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

bashiro's avatar

Fetching data from one to Many

Good day folks,

I am asking nicely for help: I have one tto many relationship models student and examsrecord

In the controller:

public function viewRegisteredResult($student_id){

  $data = Student::where('id', $student_id)->first();
  $examsrecords =Student::with('examsrecord')->where('id', $student_id)->get(); 
  
$students = StudentExams::select('exams_type', 'exams_year','subject_name', 'obtained_marks')->where('id', $student_id)->get()->all();

//dd( $examsrecords, $data);

return view ('exams.registered_result',compact('data', 'examsrecords','students'));

When I do dd( $examsrecords, $data); I get all subjects registered to the user. But when I do foreach loop in the blade I get only one row why? Any help with the blade code ?

SNIPP OF BLADE CODE @foreach ($students as $student )

 <tr>                                 
<td>{{$student->exams_type}}</td>
<td>{{$student->subject_name}}</td>

In some cases I tried
$examsrecords['examsrecords'] =StudentExams::with('student')->where('id', $student_id)->get();
still only one row shows for he user, but dd shows all.


Thanks a lot guys
Bashiro
0 likes
2 replies
tykus's avatar

I don't know what you're trying to do... your queries make no sense. Why not get the Student with its associated examrecords like this:

// $data = Student::where('id', $student_id)->first(); // NOT NEEDED
// $examsrecords =Student::with('examsrecord')->where('id', $student_id)->get(); // rubbish
$student = Student::with('examsrecord')->find($student_id);

Now, you have the $student instance, and the $student->examrecords Collection both available in the view whenever you pass $student to the template.

I have not idea what this query is about:

$students = StudentExams::select('exams_type', 'exams_year','subject_name', 'obtained_marks')->where('id', $student_id)->get()->all();

Why is the StudentExams model being queries against $student_id??? What are you actually trying to fetch here???

You need better discipline when naming your variables.

bashiro's avatar

Tykus, Thanks for your reply. I really appreciate it and it helped a lot. What I was trying to do is; to grab/fetch saved data/records of specific student using student_id and list the exams records. This is with the help of a Student:Model and a StudentExams Model with foreign key student_id. I 've now got it working by using;

    $singleStudent = StudentExams::find($student_id)->student;
      $examsrecordSingle=Student::find($student_id)->examsrecord;

return view ('exams.registered_result, compact('singleStudent', 'examsrecordSingle'));

And all the records of the single student now displays perfectly. Thanks a lot for your time.

Please or to participate in this conversation.