Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 4 Migration - Cannot add foreign key constraint

Here's my migration code:

public function up()
{
    Schema::create('foos', function(Blueprint $table) {
        // Primary key
        $table->increments('id');

        // Standard
        $table->engine = 'InnoDB';
        $table->timestamps();
        $table->softDeletes();
    });

    Schema::create('bars', function(Blueprint $table) {
        // Primary key
        $table->increments('id');

        // Define foreign key
        $table->integer('foo_id')->unsigned;

        // Foreign key contraints
        // NOTE: causes "General error: 1215 Cannot add foreign key constraint"
        // $table->foreign('foo_id')->references('id')->on('foos');

        // Standard
        $table->engine = 'InnoDB';
        $table->timestamps();
        $table->softDeletes();
    });
}

public function down()
{
    Schema::drop('foos');
    Schema::drop('bars');
}

When the code to define the foreign key constraint is not commented out, I get the following error on the command line: General error: 1215 Cannot add foreign key constraint.

Any ideas what I am doing wrong?

like image 655
StackOverflowNewbie Avatar asked Sep 25 '13 02:09

StackOverflowNewbie


1 Answers

$table->integer('foo_id')->unsigned;

should be

$table->integer('foo_id')->unsigned();

or you can use short version:

$table->unsignedInteger('foo_id');
like image 72
ceejayoz Avatar answered Sep 16 '22 19:09

ceejayoz