Johannes Johannes - 2 months ago 16
PHP Question

Laravel relationship method not working

after spending hours on solving this issue I want to ask you for help.

I have the following structure:

Model: Student.php

class Student extends Model
{
protected $table = 'studenten';

public function kurs() {
return $this->belongsTo(Kurs::class);
}
}


Model: Kurs.php

class Kurs extends Model
{
protected $table = 'kurse';

public function studenten() {
return $this->hasMany(Student::class);
}
}


Controller: KursController.php

class KursController extends Controller
{
public function showStudenten() {
return view('example.studenten', [
'kurse' => Kurs::all(),
]);
}
}


View: example\studenten.blade.php

@foreach($kurse as $kurs)
<p>{{ $kurs->title }}, {{ $kurs->id }}</p>
@foreach($kurs->studenten() as $student))
<p>{{ $student->name }}</p>
@endforeach
@endforeach


Table: kurse

id | title | created_at | updated at


Table: studenten

id | name | kurs_id | created_at | updated_at


I'm trying to output the students belonging to every course. Where is my error? I tried to specify the foreign key 'kurs_id' in my model methods but it won't work.
Could you please help me to find my mistake?

Thank you in advance.

Answer

Try this

In Your Controller

 public function showStudenten() {
    return view('example.studenten', [
        'kurse' => Kurs::with('studenten')->get(),
    ]);
}

In your view file

@foreach($kurse as $kurs)
 <p>{{ $kurs->title }}, {{ $kurs->id }}</p>
   @foreach($kurs->studenten as $student)) 
    <p>{{ $student->name }}</p>
   @endforeach
@endforeach