Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Available actions for onUpdate / onDelete in Laravel 5.x

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

like image 827
bobD Avatar asked Sep 15 '16 18:09

bobD


People also ask

What is Ondelete (' cascade ') in laravel?

ON DELETE CASCADE constraint is used in MySQL to delete the rows from the child table automatically, when the rows from the parent table are deleted.

How do I change the data type in laravel migration?

How to change data type of column in laravel 9 migration ? Step 1 : Install doctrine/dbal package. Step 2 : Generate migration file. Step 3 : Open generated migration file and update.


2 Answers

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();
like image 86
Rafael Berro Avatar answered Sep 30 '22 02:09

Rafael Berro


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"

like image 43
Jaspal Singh Avatar answered Sep 30 '22 00:09

Jaspal Singh