Search code examples
laravellaravel-5migration

How to use nullable in foregin in Laravel?


I create migration in laravel 5.6.

I need add user information if the user was logged in my website else add 0 in column.

My code is:

$table->integer('user_id')->default(0);
$table->foreign('user_id')->references('id')->on('users');

But aftre run migrate show this error:

SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint  

I need add default 0 or null in column or add user_id in column if the user was logged in my website.

How to issue this problem?


Solution

  • You need to make it unsigned and nullable. Also, it's a good idea to separate creating a column and adding foreign key logic to avoid similar errors:

    Schema::create('table_name', function (Blueprint $table) {
        $table->unsignedInteger('user_id')->nullable();
    });
    
    Schema::table('table_name', function (Blueprint $table) {
        $table->foreign('user_id')->references('id')->on('users');
    });