Mark Kendall
Mark Kendall

Reputation: 129

Laravel 4.2 cascade soft deletes in observers

I have 3 related tables / models in Laravel 4.2:

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.

Upvotes: 0

Views: 1331

Answers (1)

lukasgeiter
lukasgeiter

Reputation: 152870

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

Upvotes: 2

Related Questions