Search code examples
laravellaravel-4observers

Laravel 4.2 cascade soft deletes in observers


I have 3 related tables / models in Laravel 4.2:

  • Users
  • Posts
  • Tags

Users have posts which are tagged in a polymorphic lookup table.

Users and posts both implement soft-deletes and I am using an Observer to try and cascade the delete user event to soft-delete the users posts.

so my UserObserver has:

public function deleted($user){
    // Soft delete their posts 
    \Log::info('Soft-deleting user posts');
    $user->posts()->delete();
}

My PostObserver deleted method has:

public function deleted($post){
    // De-tag the post
    \Log::info('Detaching tags from post');
    $post->tags()->detach();
}

My issue is that while deleting the user successfully deletes their posts, the PostObserver delete method is not triggered and so the tags are not detached.


Solution

  • $user->posts()->delete(); will not trigger any model events. It will just run a DELETE query on the relationship. For Eloquent features like model events to work you have to delete them one by one with a loop:

    $user->posts->each(function($post){
        $post->delete();
    });