18

As mentioned in here, we can use the word cascade when making a relation in migrations
but I wonder they didn't say anything about other actions when deleting or updating a foreign key

so I'm not sure if there is such thing or not:

$table->foreign('user_id')
  ->references('id')->on('users')
  ->onDelete('set null');
  //->onDelete('set_null');
  //->onDelete('setNull');

or the same thing about onUpdate and about no action just like the phpMyAdmin

enter image description here


thanks

Orici
  • 411
  • 6
  • 12
bobD
  • 1,037
  • 2
  • 9
  • 17

3 Answers3

34

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();
ahmad bd
  • 53
  • 6
Rafael Berro
  • 2,518
  • 1
  • 17
  • 24
6

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"

Jaspal Singh
  • 1,210
  • 1
  • 12
  • 17
4

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();

Tushar Saha
  • 647
  • 6
  • 13