HOW TO MAKE THE INCREMENT METHOD TRIGGER MODEL EVENTS

Sep 13, 2024 Copy Link

While maintaining the Digging Code, especially the Newsletter, I attempted to increment the Newsletter count and then run the `optimize:clear` command within the Model Events but, I discovered that Laravel does not hit the Event closure, therefore, I searched about this trouble and found Dries Vints' Answer which, benefits that Laravel does not emit the Events while incrementing/decrementing for mass updates

 

In the beginning, lemme introduce the wrong way that I wrote:

 

SettingModel::where('key', 'newsletter_count')->increment('value');

 

To solve this issue, follow the upcoming approach:

 

$setting = SettingModel::where('key', 'newsletter_count')->firstOrFail();

$setting->update(['value' => $setting->value + 1]);

 

You can do that too:

 

SettingModel::where('key', 'newsletter_count')->firstOrFail()->increment('value');

 

You should look over the example that demonstrates this issue.

Share via

Filed in:

Tips Eloquent
Mahmoud Ramadan

Mahmoud Ramadan

Mahmoud is the creator of Digging Code and a contributor to Laravel since 2020.

Most recent

  • How to generate Arabic PDF using TCPDF

    How to generate Arabic PDF using...

    FREE

  • What is SQL Injection

    What is SQL Injection

    FREE

  • Leveraging virtual generated columns in MySQL using Laravel

    Leveraging virtual generated col...

    FREE