Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

bbaker's avatar

MySQL migration of foreign key constraint errors

I am trying to create foreign keys in my MySQL database using php artisan migrate and I continually get a 1005 error from the server. There are, of course, several other tables in the migration but I stripped all but the two that cause the error.

The referenced table:

class CreateAcctAddressTable extends Migration
{
    public function up()
    {
        Schema::create('foo', function (Blueprint $table) {
            $table->engine = "InnoDB";
            $table->increments('id');
            ...
        }
    }
}

The referencing table:

1 class CreateAcctAddressTable extends Migration
2 {
3     public function up()
4     {
5         Schema::create('bar', function (Blueprint $table) {
6             $table->engine = "InnoDB";
7             $table->increments('id');
8             $table->integer('foo_id')->unsigned();
9             ...
10             $table->index('foo_id');
11             $table->foreign('foo_id','fk_cc_addr_ix')->references('foo')->on('id')->onDelete('cascade')->onUpdate('cascade');
12         }
13     }
14 }

I found several very good suggestions for the source of my errors at this link but I could not see any that was violated in my situation.

I understand that line 10 is not necessary since the foreign() method should create one automatically but I put it in out of desperation.

I also tried several other versions of line 11:

$table->foreign('foo_id')->references('foo')->on('id');
$table->foreign('foo_id','fk_cc_addr_ix')->references('foo')->on('id');

Any ideas?

0 likes
1 reply

Please or to participate in this conversation.