Modify and Persist Model Instances in Laravel Using the saved Event, Not the saving Event

In Laravel, don’t call the save method on a model instance inside the saving event listener.

If you need to modify a model’s field and persist it within a model event listener, make sure you’re using the saved event, not the saving event. This is particularly important when your event listeners are queued for asynchronous execution.

The saving event occurs before the model is persisted to the database. If you try to modify a field and call save() within this listener, it won’t actually persist to the database, especially when the listener is queued for async execution. For example, modifying the slug field might not actually update in the database.

Instead, use the saved event listener and call saveQuietly to persist the changes, as shown in the example:

static::saved(queueable(function (Topic $topic) {
    // If the slug is empty, translate the title into a slug
    if (!$topic->slug) {
        $topic->slug = app(SlugTranslateHandler::class)->translate($topic->title);
        $topic->saveQuietly();
    }
}));

By using the saved event and saveQuietly, you ensure that your changes are made after the model is successfully persisted, avoiding any issues with asynchronous queue execution.

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注