Laravel - Collection::delete method does not exist

In your deleting listener you are trying to delete something else, which is a Collection which is causing the error.

$user->posts is a relationship to Posts which is a plural which is a hasMany relationship (most likely) so it returns a Collection always. Collections do not have a delete method. You will have to iterate through the collection and call delete on each Post

// calling `delete()` on a Collection not a Model
// will throw the error you see
$user->posts->delete();

// iterate through the Collection
foreach ($user->posts as $post) {
    $post->delete();
}

Side Note: you can not do any action in bulk with Models and queries and have the events be fired. All Model events are based on single instances of the Models. A direct query bypasses the Model.


You can optimise lagbox's answer by using only one query to delete all of the posts. In his example he's executing a delete query for every post attached to the user.

For a single delete query either use the query builder of the relationship directly:

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

or use the pluck method of the collection and a separate query:

Post::where('id', $user->posts->pluck('id'))->delete();

You can use higher order messages as well:

$user->posts->each->delete();