user6073700 user6073700 - 4 months ago 19
MySQL Question

Laravel 5.2 Foreign Key fails

I am trying to add a foreign key in my posts table to reference the id in the users table. Here are my migrations, the users table is the default one packed with laravel so the timestamps are from NOV 2014 however the posts is one I created. Any help greatly appreciated.

Thanks a lot :)

Users migration


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

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

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


posts migration

<?php

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

class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id')->unsigned();
$table->string('title');
$table->string('section');
$table->string('body');
$table->date('post_created_date');
$table->integer('author_id')->unsigned()->after('id');
$table->foreign('author_id')->references('id')->on('users');
$table->timestamps();
});
}

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


Every time I migrate I get the following error:

ERROR

Answer

If you are creating a table, you don't want to use after as it will create a syntax error. Just place the column where you want it. I believe after will only work for alter table statements.

    Schema::create('posts', function (Blueprint $table) {
        $table->increments('id');  // Unsigned is assumed for increments so I removed that as well
        $table->integer('author_id')->unsigned();
        $table->string('title');
        $table->string('section');
        $table->string('body');
        $table->date('post_created_date');
        $table->timestamps();
        $table->foreign('author_id')->references('id')->on('users');
    });
Comments