jeudi 26 juillet 2018

Why does collection->where() return index number?

I'm sure this may be a simple solution, but I can't seem to work it out.

I am trying to use Laravel's where() clause to build an array of $courses that belong to each $student. I cycle through each $student and filter the $courseRecords to find matching courses based on their StudentCode.

Here is my sample code snippet:

// Cycle through the students and add their relevant course details
foreach( $students as $student ) {

    // Find matching courses to the student
    $courses = $courseRecords->where( 'StudentId', $student->StudentCode );

    // Add the course array to the student record
    $student->Courses = $courses;

}

However, the result I get, gives me each student's course, but with a leading index number (as shown below in random results):

enter image description here

I can't seem to work out why this is happening. The first entry (Id 0) is the result I am expecting, but for some reason, every other result seems to give me the matching index number of $courseRecord.

I have tried using $courses->all(); and $courses->toArray(); but this doesn't make any difference. From the Laravel documentation (that I have read), it doesn't mention this behaviour which makes me think I have something incorrect.

$students and $courseRecords are both a collection.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire