0

I am using laravel 9, PHP 8.1.

I noticed the following problem:

// App\Model\Store

class Store extends Model
{
    ....

    public function scopeUpdateStore($query, $id) {
        Store::find($id)->update(['name' => 'foo']);
        return $query;
    }
}

Then if I use :

Store::updateStore($id)->first();

Event updating and updated will not fire.

But when I use in controller:

// StoreController

Store::find($id)->update(['name'])

Event updating and updated will fire.

My problem is that it is not clear why there is this difference, and is there a way to make the event fireable in the Query Scope?

Thank you very much.

steven7mwesigwa
  • 5,701
  • 3
  • 20
  • 34
KingNNT
  • 11
  • 2
  • 4
  • I'm curious to know why you're using [Local Scopes](https://laravel.com/docs/9.x/eloquent#local-scopes) to perform database updates. *Local scopes allow you to define common sets of **query constraints** that you may easily re-use throughout your application.* – steven7mwesigwa Oct 07 '22 at 10:17
  • It is also most likely because the `name` column value for that updated Model was already set to `'foo'` prior. Hence, no actual changes were made. Effectively, no model events would be fired in that case. – steven7mwesigwa Oct 07 '22 at 10:28
  • 1
    Does this answer your question? [How to manually trigger Laravel model event](https://stackoverflow.com/questions/60597719/how-to-manually-trigger-laravel-model-event) – steven7mwesigwa Oct 07 '22 at 10:29
  • First, you need to know we're not doing any CURD inside the model. As you said ***But when I use in controller Event updating and updated will fire.*** Cz that's how it meant to work – Abdulla Nilam Oct 07 '22 at 12:55
  • that is not what scopes are for, you just want to define a regular method to call ... – lagbox Oct 07 '22 at 13:20
  • @steven7mwesigwa My intention when using update at query scope will be for updating more information from related tables like images or categories of store for example. I think it's like if I extend the `update` method, instead of updating the information in one table, I will update the related tables. – KingNNT Oct 10 '22 at 02:51

0 Answers0