0

Using Laravel + Voyager, I have a "Has Many" relationship:

Course hasMany Teachers.

In backend all is fine, but if I try to get the information in the frontend, I only get the value in table, not the relation, so the output goes something like:

0   
id  1
teachers_id null
name    "Math"

1   
id  2
teachers_id null
name "English"

Current code in web routing:

Route::get('/course', function () {
    $co= App\Course::all();
    return $co;
});

How can I get the correct output?

teachers_id Xav, Titus
pxs
  • 77
  • 6

1 Answers1

1

so like @Tpojka commented you can start by eager loading the relationship when you are initializing the course likeso $co = App\Course::with('teachers')->get(); after which you do not need to make another unnecessary call to your database for the teachers of that course. You can get a collection of all the teachers of that course by simply calling $teachers = $co->teachers; here $teachers is now a laravel collection you can simply loop through it on the client side and display the information about the teachers you want to display. I hope this helps.

Good luck and happy coding. :)