Reputation: 1036
I have a table of "rosters" that's pretty much strictly foreign keys. It acceses the "schools" table, "courses" table, and "students" table. So essentially, a 'student' takes a 'course' at a 'school'. My RostersController has this
public function show($id)
{
$roster = Roster::where('course_id', $id);
return view('roster')->with('roster', $roster);
}
My Roster Model is:
public function students()
{
return $this->hasMany('App\Student');
}
My student Model is:
public function roster()
{
return $this->belongsTo('App\Roster');
}
my view is this:
@foreach ($roster as $child)
<p>{{$child->id}}</p>
<p>{{$child->students->first_name}}</p>
@endforeach
The rosters table just saves the student_id rather than all of the student's data that is already in the 'students' table. So i'm trying to access the students table from this relation but when i run this, it tells me that anything related to the students table is 'not on this collection'. I know that I could do things this way if i was working with a hasOne relationship, but how can i accomplish this with a hasMany to output the students table value in each row?
Upvotes: 1
Views: 1364
Reputation: 1006
So, your first issue is, that
$roster = Roster::where('course_id', $id);
will just return a QueryBuilder instance, you have to use
$roster = Roster::where('course_id', $id)->get();
then for sure, students is a collection, you have to iterate over it like this:
@foreach ($child->students as $student)
{{ $student->yourProperty}} <br>
@endforeach
Update: I saw you know already about that when to use get() in query laravel 5
Upvotes: 0
Reputation: 5609
The $child->students
is a collection. So, you need to use another foreach
loop inside the first one.
Your code should look like this:
@foreach ($roster as $child)
<p>{{$child->id}}</p>
@foreach($child->students as $student)
<p>{{$student->first_name}}</p>
<p>{{$student->age}}</p>
<p>{{$sutdent->another_column_in_students_table}}</p>
@endforeach
<p>{{$child->any_other_column_in_roster_table_if_needed}}</p>
@endforeach
Upvotes: 0
Reputation: 2523
Try this
Roster.php
public function show($id)
{
$roster = Roster::with('students')->where('course_id', $id)->get(); // load the students
return view('roster')->with('roster', $roster);
}
On the view
@foreach ($roster as $child)
<p>{{$child->id}}</p>
<p>
<!-- Loop through the stundents since this returns an collection of students and not just one -->
@foreach($child->students as $student)
{{$student->first_name}} <br>
@endforeach
</p>
@endforeach
Check this for more information on eager loading
Upvotes: 0
Reputation: 773
You should try this
public function show($id)
{
$roster = Roster::with('students')->where('course_id', $id);
return view('roster')->with('roster', $roster);
}
Upvotes: 0