afterSave() is not triggered on Collection->update();

I got an afterSave() method in my model which removes a certain cache if the model is saved.

But in order to check if the afterSave() was triggered, I simply added a trace_log().

Now when I edited the Model in the edit view, afterSave() was triggered correctly.

Also the listSwitch is doing its job - this here is the code for documentation purposes:

        $item = $modelClass::findOrFail($id);
# ...do something
        $item->save();

Now my handler does not trigger the afterSave() method, here’s the code:

    public function onPublishUp()
    {
        $checkedIds = HandlerHelper::getCheckedIds(); # Returns an array of checked IDs
        MyModel::whereIn('id', $checkedIds)->where('published', false)->update([
            'published_at' => Carbon::now(),
            'published' => true
        ]);
    }

Basically the handler still does its job, but it does NOT call the afterSave() method.

Now I looked it up when afterSave() should be called:

afterSave after the model is saved, either created or updated.

But I also saw this:
afterUpdate after an existing model is saved.

So I also implemented the afterUpdate() and see when it was called: Worked with the listswitch, worked with the edit form, didnt work with the handler, same as afterSave()

So now I wonder… did I miss something or is this a bug?

MyModel::whereIn('id', $checkedIds)->where('published', false)

This code returns query builder. Not model or collection. So it is not calling afterSave or afterUpdate.

3 Likes
        $models = MyModel::whereIn('id', $checkedIds)->where('published', false)->get();
        foreach ($models as $model) :
            $model->published_at = Carbon::now();
            $model->published = true;
            $model->save();
        endforeach;

Ah, missed that part! Thanks a lot! The solution will trigger more queries now, but calling afterSave() and cleaning the cache safely is more important for me in a backend handler.

Thanks