Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cascade on softdeletes in Laravel4?

Tried to use foreign keys with delete cascade and softDeletes without much luck.

I have 2 tables: Users, Events. Both tables have softDeletes.

Users can have 0..n Events.
Events have an user_id, used as foreign key on users, like this:

$table->foreign('user_id')->references('id')->on('users')->onDelete('CASCADE')->onUpdate('CASCADE');

Problem is, when I delete an User, it gets soft-deleted, but its Events do not - either soft deletion or physical deletion.

Am I doing something wrong, or is this the correct Eloquent behavior?

Secondly, if that is the correct behavior, how to best implement deletion cascade? maybe overriding the delete() method in my Models like this ...

public function delete()
{
  //delete all events...
  __parent::delete()
}

?

like image 806
RedSash Avatar asked Jul 31 '13 18:07

RedSash


2 Answers

The DB's foreign key won't do anything because you haven't changed the primary key in question. Only if you update or delete the primary key will the related rows be modified.

From everything I can find about this topic, the solution is to use Eloquent's Model Events to listen for a delete event, and update the related tables.

Here's one StackOverflow question about it.

Alternatively, you can "extend" the delete() method and include the functionality directly as well. Here's an example.

like image 178
Aken Roberts Avatar answered Oct 22 '22 12:10

Aken Roberts


You're overthinking this.

Either just delete the events right before you delete the users:

$user->events()->delete();
$user->delete();

Or create a customer delete function in the user model:

public function customDelete(){
    $this->events()->delete();
    return $this->delete();
}

You could also add a model observer and watch for the deleting or delete event, but in the scenario you mentioned above, the previous two methods would be a more simple solution.

http://laravel.com/docs/4.2/eloquent#model-observers

like image 44
Jeremy Gehrs Avatar answered Oct 22 '22 12:10

Jeremy Gehrs