Mohammad
Mohammad

Reputation: 87

Migration: Cannot add foreign key constraint in Laravel 6

I'm trying to create foreign keys in Laravel. However, when I migrate my table using Artisan, I get the following error.

Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table posts add constraint posts_category_id_foreign foreign key (category_id) references categories (id))

Posts migration

Schema::create('posts', function (Blueprint $table) {
    $table->uuid('id')->primary();
    $table->string('title');
    $table->string('slug')->unique();
    $table->longText('content');
    $table->string('image')->nullable();
    $table->uuid('author_id');
    $table->uuid('category_id');
    $table->timestamps();
    $table->foreign('author_id')->references('id')->on('users')->onDelete('set null');
    $table->foreign('category_id')->references('id')->on('categories')->onDelete('set null');
});

Categories migration

Schema::create('categories', function (Blueprint $table) {
    $table->uuid('id')->primary();
    $table->string('name');
    $table->string('slug')->unique();
    $table->uuid('parent')->nullable();
});

Upvotes: 0

Views: 383

Answers (2)

José A. Zapata
José A. Zapata

Reputation: 1297

In your posts schema you're setting the author_id and category_id as null on deleting, but you didn't set those fields as nullable. Changing the definition to:

$table->uuid('author_id')->nullable();
$table->uuid('category_id')->nullable();

should do it.

Upvotes: 2

James Allen
James Allen

Reputation: 1019

Split your foreign key declarations in to their own Schema method...

I don't understand the cause of the problem, but doing this has always worked for me.

Schema::create('posts', function (Blueprint $table) {
    $table->uuid('id')->primary();
    $table->string('title');
    $table->string('slug')->unique();
    $table->longText('content');
    $table->string('image')->nullable();
    $table->uuid('author_id');
    $table->uuid('category_id');
    $table->timestamps();
});

Schema::table('posts', function(Blueprint $table) {
    $table->foreign('author_id')->references('id')->on('users')->onDelete('set null');
    $table->foreign('category_id')->references('id')->on('categories')->onDelete('set null');
});

Upvotes: 1

Related Questions