0
votes

I get this error while trying to migrate:

SQLSTATE[HY000]: General error: 1005 Can't create table testing.#sql-1848_3ae (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table gallery add constraint gallery_user_id_foreign foreign key (user_id) references users (id))

[PDOException] SQLSTATE[HY000]: General error: 1005 Can't create table testing.#sql-1848_3ae (errno: 150 "Foreign key constraint is incorrectly formed")

here are my migrations:

class CreateUsersTable extends Migration
{
    /**
    * Run the migrations.
    *
    * @return void
    */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
   }

   /**
   * Reverse the migrations.
   *
   * @return void
   */
   public function down()
   {
       Schema::drop('users');
   }
}
class CreateGalleryTable extends Migration
{
    /**
    * Run the migrations.
    *
    * @return void
    */
    public function up()
    {
        Schema::create('gallery', function (Blueprint $table) {
            $table->increments('id');
            $table->string('description')->nullable();
            $table->integer('user_id');
            $table->timestamps();
            $table->foreign('user_id')->references('id')->on('users');
        });
    }

    /**
    * Reverse the migrations.
    *
    * @return void
    */
    public function down()
    {
        Schema::drop('gallery');
    }
}
1

1 Answers

1
votes

I don't believe you can set a forgein key within the Schema::create();

Add this within your up method, but outside of the Schema::create();

Schema::table('gallery', function ($table) {
    $table->integer('user_id')->unsigned();
    $table->foreign('user_id')->references('id')->on('users');
}

Also, consider adding the following to your down() function. I have run into issues trying to reset migrations and not working due to the Foreign Key Constraints. $table->dropForeign('gallery_user_id_foreign');