Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Husniddin's avatar

Observers not working when call model update without get()

Observers not working while calling model update without get()

App\Models\Nurse::query()->where('id', 1)->update(['first_name'=>'Sardor2']);

observers not working

But If I use like

$model = App\Models\Nurse::query()->where('id', 1)->first();

$model->update(['first_name'=>'Sardor2']);

Working.

How to fix it?

0 likes
2 replies
LaryAI's avatar
Level 58

Observers in Laravel are used to hook into various points of a model's lifecycle, such as when it is being created, updated, deleted, etc. However, observers are only triggered when performing these actions on a model instance, not on a query builder instance.

When you use the update method directly on the query builder, like this:

App\Models\Nurse::query()->where('id', 1)->update(['first_name'=>'Sardor2']);

You are bypassing the model's events system, and thus the observers will not be triggered. This is because the update method on the query builder is a direct database operation that does not instantiate the model and does not fire any model events.

On the other hand, when you retrieve the model first and then call update on the model instance:

$model = App\Models\Nurse::query()->where('id', 1)->first();
$model->update(['first_name'=>'Sardor2']);

This will trigger the model's saving, saved, updating, and updated events because you are working with a model instance, and observers will work as expected.

To fix the issue, you need to retrieve the model instances first and then perform the update operation on each instance. If you need to update multiple records and still want to use observers, you can loop through the models:

$models = App\Models\Nurse::query()->where('some_condition', 'value')->get();

foreach ($models as $model) {
    $model->update(['first_name' => 'Sardor2']);
}

This will ensure that for each model, the update is performed through the model instance, and all the appropriate events are fired, allowing the observers to work correctly.

If you have a large number of records to update and are concerned about performance, you might need to reconsider whether observers are the right choice for this operation, as they can introduce overhead. In such cases, you might need to use a different approach, such as dispatching jobs to handle each update or using model events more selectively.

1 like

Please or to participate in this conversation.