I have a many-to-many relationship created between USERS and COURSES. The models and migrations are made as follows.
User Model:
public function courses()
{
return $this->belongsToMany(Course::class)->withTimestamps();
}
Course Model:
public function users()
{
return $this->belongsToMany(User::class, 'course_user', 'course_id', 'user_id')->withTimeStamps();
}
The problem is I cannot find a way to implement a composite primary key into my migration file or pivot table in Laravel like this,
Schema::create('course_user', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->integer('course_id')->unsigned()->index()->primary();
$table->foreign('course_id')->references('id')->on('courses');
$table->integer('user_id')->unsigned()->index()->primary();
$table->foreign('user_id')->references('id')->on('users');
});
After coding the above, when I call php artisan migrate:refresh
an error appears showing multiple primary keys performed in the linked table. So I did a research on this matter and found out that ELOQUENT does not support composite primary keys as stated in this forum: link to the forum
Is there any other way I can go around this? I have somehow managed to write a piece of code to detect a existing entries in the pivot table or the many-to-many relationship, inside the controller and avoid new duplicate entries.