Set a foreign key to nullable in laravel

  foreign-keys, laravel, laravel-8, mysql

Assume I have a the tables users and persons. An entry in persons can have a user id or not. So a person can have a user, but this is optional.

This means that the foreign key in persons needs to be nullable.

This is my database migration:

$table->bigInteger('user_id')->nulleable()->unsigned();
$table->foreign('user_id')->nulleable()->references('id')->on('users');

Sadly, when I check the database columns it says, that the field is not nullable

+------------+-----------------+------+-----+---------+----------------+
| Field      | Type            | Null | Key | Default | Extra          |
+------------+-----------------+------+-----+---------+----------------+
| user_id    | bigint unsigned | NO   | MUL | NULL    |                |
+------------+-----------------+------+-----+---------+----------------+

How can I set the foreign key to nullable? I have tried various combinations I found online, but nothing works.

Thank you very much in advance.

Source: Laravel

Leave a Reply