user154's avatar

Model Event Using Closure

I was a little confused when using this function

protected static function booted()
{
     static::deleted(function ($user) {
         //
     });
 }

if i using

User::find()->delete()

the deleted event will triggered but the record in database are not removed, but if i using

User::where()->delete()

record are removed but deleted event not triggered, i want to know why?

0 likes
5 replies
martinbean's avatar

@user154 Because you‘re deleting (potentially) many records via a where clause and not a single model instance. Events are raised in that case.

1 like
kevinbui's avatar
kevinbui
Best Answer
Level 41

This is pretty straightforward, elaborating on @martinbean point. Let's talk about this statement first.

User::where()->delete();

That delete method is the Illuminate\Database\Eloquent\Builder::delete() method. It will create a single DB statement to remove the users, and Laravel has no idea which records have been removed.

The second option:

User::find(1)->delete();

// Or
User::where()
    ->get()
    ->each(fn (User $user) => $user->delete());

Now the delete method is the Illuminate\Database\Eloquent\Model::delete() method. We retrieve the user first, so Laravel has an idea what users we have. And when we delete each user object, the deleted event will be fired.

puklipo's avatar

When using Laravel's Database, it's important to understand the difference between Eloquent and Query Builder.

Processing is automatically transferred from Eloquent to Query Builder. Even if you are using App\Models\User, you cannot say "I am using Eloquent."

Please or to participate in this conversation.