Laravel Eloquent create composite key that uses autoincrements Laravel Eloquent create composite key that uses autoincrements laravel laravel

Laravel Eloquent create composite key that uses autoincrements


I assume that you're using MySQL.

First of all, the default MySQL engine InnoDB doesn't allow composite primary keys where one of the fields would be autoincrement. The engine that allows that is MyISAM, so the first thing you need to do is to change the engine for the table.

You can do that by adding the following to your table definition:

$table->engine = 'MyISAM';

The next issue you need to tackle is the fact that Laravel's schema builder assumes, that the column you set as autoincrement is your primary key. That;s why you're getting the error about primary key existing already - Laravel already made the id field the primary key.

To solve this issue, you need to declare id field as normal integer column, define all other columns and at the end declare the composite primary key. It could look like that:

$table->integer('id');$table->integer('order_num');$table->timestamps();$table->primary(['course_id', 'order_num']);

This way you have created a composite primary key. The only thing that is missing is the autoincrement attribute on id column. Laravel's schema builder doesn't provide methods to alter existing columns, that's why you'll need to run raw SQL queries. The query you need is:

DB::statement('ALTER TABLE my_table MODIFY id INTEGER NOT NULL AUTO_INCREMENT');

To sum up, your migration's up() method could look like following:

public function up(){  Schema::create('my_table', function (Blueprint $table) {    $table->engine = 'MyISAM';    $table->integer('id');    $table->integer('order_num');    $table->timestamps();    $table->primary(['course_id', 'order_num']);  });  DB::statement('ALTER TABLE my_table MODIFY id INTEGER NOT NULL AUTO_INCREMENT');}