Search code examples
mysqldatabaselaravelmigration

Laravel migration can't add foreign key


I'm trying to write a laravel database migration but I'm getting the following error about a foreign key:

  [Illuminate\Database\QueryException]                                                                                                                                                                                                                    
  SQLSTATE[42000]: Syntax error or access violation: 1072 Key column 'category_id' doesn't exist in table (SQL: alter table `subcategories` add constraint subcategories_category_id_foreign foreign key (`category_id`) references `categories` (`id`))  



  [PDOException]                                                                                           
  SQLSTATE[42000]: Syntax error or access violation: 1072 Key column 'category_id' doesn't exist in table 

The categories and subcategories tables do get created but the foreign key doesn't. Here's my migration:

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateCategoryTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('categories', function ($table) {
            $table->increments('id')->unsigned();
            $table->string('name')->unique();
        });

        Schema::create('subcategories', function ($table) {
            $table->increments('id')->unsigned();
            $table->foreign('category_id')->references('id')->on('categories');
            $table->string('name')->unique();
        });
    }

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

Any ideas? Thanks!


Solution

  • You should create column before creating a foreign key:

    $table->integer('category_id')->unsigned();
    $table->foreign('category_id')->references('id')->on('categories');
    

    Documentation: http://laravel.com/docs/5.1/migrations#foreign-key-constraints