Laravel’s DB Facade Doesn’t Trigger Eloquent ORM Model Events

When using the DB facade to perform database operations in Laravel, Eloquent ORM model events like saving, saved, etc., are not triggered.

If you want to avoid triggering model events in event listeners or queued tasks, aside from using Eloquent’s saveQuietly, deleteQuietly, and similar methods, you can directly use the DB facade to execute database operations.

This approach allows you to bypass Eloquent’s event handling when necessary.

Laravel使用DB façade执行数据库操作不会触发Eloquent ORM模型事件

使用DB façade执行数据库操作不会触发saving、saved等Eloquent ORM模型事件。当我们不想在事件监听器或队列任务中触发Eloquent ORM模型事件时,除了使用Eloquent ORM模型的saveQuietly、deleteQuietly等方法之外,还可以直接使用DB façade执行数据库操作。

在Eloquent ORM模型事件监听器和队列任务中,要避免使用Eloquent模型增删改查方法,例如create、update、save等。否则会陷入调用死循环 —— 模型事件监听器分发队列任务,队列任务触发模型事件,模型事件监听器再次分发队列任务,队列任务再次触发模型事件……死循环了。