Laravel Database Schema, Nullable Foreign Laravel Database Schema, Nullable Foreign laravel laravel

Laravel Database Schema, Nullable Foreign


Set the country_id and the state_id nullable, like so.

$table->integer('country_id')->nullable()->unsigned();$table->integer('state_id')->nullable()->unsigned();


For laravel 7.x to create a nullable foreign key use simply:

$table->foreignId('country_id')->nullable()->constrained();$table->foreignId('state_id')->nullable()->constrained();

REMEMBER: nullable should be before constrained otherwise the nullable will not be affected.


With the latest version of Laravel, you can use the nullable method in conjunction of foreignKey:

$table      ->foreignId('other_table_id')      ->nullable() // here      ->references('id')      ->on('other_table');