Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Schema onDelete set null

If you want to set null on delete:

$table->...->onDelete('set null');

First make sure you set the foreign key field as nullable:

$table->integer('foreign_id')->unsigned()->nullable();

In laravel 8 you can use:

$table->foreignId('forign_id')->nullable()->constrained("table_name")->cascadeOnUpdate()->nullOnDelete();

Reference

The different options are declared in class Illuminate\Database\Schema\ForeignKeyDefinition (see source).


  • This is a known issue in Laravel. More info about this here.

  • This feature is not supported in SQLite, see here

  • Also a topic that has a detailed showdown of this problem


According to

http://dev.mysql.com/doc/refman/5.6/en/innodb-foreign-key-constraints.html

$table->onDelete('set null') should work prehaps try

$table->...->onDelete(DB::raw('set null'));

If there are any errors, would also be helpful


Using Laravel 4.2 on MySQL 5.5 with InnoDB, onDelete('set null') works.


in laravel 8 you can do it like this.

 $table->foreignId('table_id')->nullable()->constrained()->onDelete('set null');

nullable() column modifiers must be called before constrained() and onDelete('set null')