Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fire Laravel (5.6) Event when Model is deleted?

Tags:

laravel

I'm trying to fire an Event when a User is deleted from the system but I'm thinking it's deleting my user too quickly so my Event isn't working. What I'm looking to do is broadcast when a User is deleted.

Here's the controller:

public function destroy($id)
{
    $user = new User();

    $user = $user->find($id);

    broadcast(new UserWasDeleted($user, Auth::user()))->toOthers();

    $user->delete();

    return response([
                        'status'  => 'success',
                        'message' => 'The user was successfully deleted.'
                    ], 200);
}

This successfully broadcasts if I remove the $user->delete(); line, and doesn't broadcast when it is in there.

I've even tried setting up a Listener for the Event, and deleting the User in the Listener. It deletes the user, but still does no broadcasting.

like image 808
Octoxan Avatar asked Jan 27 '23 20:01

Octoxan


1 Answers

The SerializesModels trait needs to be removed from events that deal with deleted models.

SerializesModels is a trait that only stores the id of the model when the event (or job) is serialized, and refetches the model from the database when the event is unserialized.

This allows queued processes to get a fresh model from the database when they run so they are not running with outdated information, but this would not be reliable when you're deleting that row from the database.

like image 118
Devon Avatar answered Feb 05 '23 16:02

Devon