Ginz77
Ginz77

Reputation: 73

Laravel: Retrieving Data in Loop in a One to Many Relationship

I'm using Laravel 5.8. Here's my code...

CreateSchoolsTable migration

public function up()
{
    Schema::create('schools', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->timestamps();
    });
}

CreateStudentsTable migration

public function up()
{
    Schema::create('students', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedBigInteger('school_id');
        $table->string('first_name');
        $table->timestamps();
    });
}

School model

class School extends Model
{
    public function students()
    {
        return $this->hasMany('App\Student');
    }
}

Student Model

class Student extends Model
{
    public function school()
    {
        return $this->belongsTo('App\School');
    }
}

Controller

class SchoolsController extends Controller
{
    public function index()
    {
        $schools = School::all();

        return view('schools.index', compact('schools'));
    }
}

My view: views>schools>index.blade.php

@foreach ($schools as $school)
    {{ $school->students->first_name }}
@endforeach

I want to display all the first names in the loop and $school->students->first_name gives me an error.

Property [first_name] does not exist on this collection instance. (View: /Users/philginsburg/Laravel/project1/resources/views/schools/index.blade.php)

When I echo out $school->students it displays an array of the students table, but not sure why I cant loop through with the field name like first_name.

Upvotes: 1

Views: 5324

Answers (2)

Alberto
Alberto

Reputation: 12929

In this case you are dealing with 2 Collections: schools and students (of each school), so you should use 2 different loop to loop through those collections, like this:

@foreach ($schools as $school)
    <p>In this school there are those students:</p>
    <ul>
       @foreach($school->students as $student)
           <li>{{ $student->first_name }}</li>
       @endforeach
    </ul>
@endforeach

Upvotes: 2

Andy Song
Andy Song

Reputation: 4684

The reason is $school->students is array, there is no property called first_name.

you need to

@foreach ($school->students as $student)
    {{ $student->first_name }}
@endforeach

Upvotes: 1

Related Questions