Is it possible to temporarily disable event in Laravel?

前端 未结 7 1614
轮回少年
轮回少年 2020-12-16 10:21

I have the following code in \'saved\' model event:

Session::flash(\'info\', \'Data has been saved.\')` 

so everytime the model is saved I

7条回答
  •  鱼传尺愫
    2020-12-16 10:56

    There is a nice solution, from Taylor's Twitter page:

    Add this method to your base model, or if you don't have one, create a trait, or add it to your current model

    public function saveQuietly(array $options = [])
    {
        return static::withoutEvents(function () use ($options) {
            return $this->save($options);
        });
    }
    

    Then in you code, whenever you need to save your model without events get fired, just use this:

    $model->foo = 'foo';
    $model->bar = 'bar';
    
    $model->saveQuietly();
    

    Very elegant and simple :)

提交回复
热议问题