Available actions for onUpdate / onDelete in Laravel 5.x Available actions for onUpdate / onDelete in Laravel 5.x laravel laravel

Available actions for onUpdate / onDelete in Laravel 5.x


You can do all the options mentioned in phpmyadmin this way:

$table->...->onDelete('CASCADE');$table->...->onDelete('SET NULL');$table->...->onDelete('RESTRICT');// do not call the onDelete() method if you want the RESTRICT option.

You have to make sure you set the foreign key field as nullable:

$table->...->unsigned()->nullable();


Referring to the source code:

`vendor/laravel/framework/src/Illuminate/Database/Schema/Grammars/Grammar.php` in the function compileForeign()

It just appends whatever you pass in to the table query.

    if (! is_null($command->onDelete)) {        $sql .= " on delete {$command->onDelete}";    }    if (! is_null($command->onUpdate)) {        $sql .= " on update {$command->onUpdate}";    }

So, make sure you pass one of the following: "cascade", "no action", "restrict", or "set null"

NOTE: Do NOT use underscores in the actions like "set_null" and "no_action"


onUpdate is also available

$table->foreign('user_id')->references('id')->on('users')->onDelete('SET NULL')->onUpdate('SET NULL'); // also available CASCADE, RESTRICT, DO NOTHING, NO ACTION

To use 'SET NULL' you have to make sure field is nullable

$table->integer('user_id')->nullable();