Laravel Database Schema, Nullable Foreign
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.
Set the country_id
and the state_id
nullable, like so.
$table->integer('country_id')->nullable()->unsigned();
$table->integer('state_id')->nullable()->unsigned();
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');
For Laravel 7.x I use this way:
$table->bigInteger('word_type_id')->nullable()->unsigned();
$table->index('word_type_id')->nullable();
$table->foreign('word_type_id')->nullable()->references('id')->on('word_types')->onDelete('cascade');