In many to many, both relationships need to be defined as return $this->belongsToMany(Model::class);
https://laravel.com/docs/5.3/eloquent-relationships#many-to-many
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I have a problem to retrieve data from two tables (courses and profiles) between which a many-to-many relationship exists, probably because one of them (profiles) is a relational table.
Model: Course
public function profiles()
{
return $this->hasMany('App\Profile');
}
Model: Profile
protected $ primaryKey = "user_id";
public $incrementing = false;
public function courses()
{
return $this->belongsToMany('App\Course');
}
Pivot table: course_profile
$table->integer('profile_id')->unsigned()->index();
$table->foreign('profile_id')->references('user_id')->on('profiles')->onDelete('cascade');
$table->integer('course_id')->unsigned()->index();
$table->foreign('course_id')->references('id')->on('courses')->onDelete('cascade');
$table->primary(['profile_id', 'course_id']);
Controller: PageController
public function courses()
{
$courses = Course::all()->load('profiles');
return view('pages.courses', compact('courses'));
}
View: courses.php
@foreach($courses as $course)
@foreach($course->profiles as $profile)
{{ $ profile -> last_name}}
@endforeach
@endforeach
Error message: Column not found: Unknown column 'profiles.course_id' in 'where clause' (SQL: select * from `profiles` where `profiles`.`course_id` in (1, 2, 3, 4, 5))
In many to many, both relationships need to be defined as return $this->belongsToMany(Model::class);
https://laravel.com/docs/5.3/eloquent-relationships#many-to-many
Please or to participate in this conversation.