"General error: 1005 Can't create table" using Laravel

If you're getting the following error when attempting to run a migration, you might be trying to add a foreign key on a parent field that doesn't exist yet.

SQLSTATE[HY000]: General error: 1005 Can't create table 'posts.#sql-XXXX' (errno: 150)

SQL: ALTER TABLE `comments` ADD CONSTRAINT comments_post_id_foreign FOREIGN KEY (`post_id`) REFERENCES `posts` (`id`) ON DELETE cascade ON UPDATE cascade

In the above example migration, the comments table is being created before the posts table, and a foreign key that references the id field in the posts table is attempting to be added. But since the posts table doesn't exist yet, it's resulting in an error.

Solution: Make sure the Schema::create() calls are in the right order, i.e. Schema::create('posts') has to come before Schema::create('comments').

Schema::create('posts', function($table) {
    $table->increments('id');
    ...
});

Schema::create('comments', function($table) {
    $table->increments('id');
    $table->integer('post_id')->unsigned()->index();
    ...
    $table->foreign('post_id')->references('id')->on('posts')->on_update('cascade')->on_delete('cascade');
});

If your Schema::create() calls are in separate migration files, you just need to change the order in which the files are processed during the migration. To do so, change the timestamp values in the names of the migration files so that the files get run in the correct chronological order.

2013_04_14_233507_create_posts.php
2013_04_14_233508_create_comments.php

Then, when you run php artisan migrate, the create_posts migration file will be processed before the create_comments migration file.

plmarcelo Dec 5, 2013

Thanks a lot!!!!! spent a lot of time finding the way to set migration order

Adam Dec 16, 2013

This really helps clarify some things with Laravel and FKs. The docs are almost silent about the workings of this. Could you also go over how to rollback properly? Nearly every time I try rolling back I've somehow messed up the Schema::drop() business and end up truncating the DB simply to try again.

puntora Jan 22, 2014

Great man! you save my life, thanks for sharing!

Ario Wicaksono Mar 23, 2014

good job

Dejan Apr 19, 2014

ive create separated migration file called add_foreign_keys and keeping up that timestamp of that file is always last.

Kenold Beauplan May 9, 2014

Thanks. Changing the Timestamps in the file name solved my problem.

Raimundo Aranha May 4, 2016

Fine. It's works. This guidance solved the problema. Many thanks

Leave a Comment