Is it possible to temporarily disable event in Laravel?

前端 未结 7 1598
轮回少年
轮回少年 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:46

    Solution for Laravel 8.x

    With Laravel 8 it became even easier, just use saveQuietly method:

    $user = User::find(1);
    $user->name = 'John';
    
    $user->saveQuietly();
    
    

    Laravel 8 docs


    Solution for Laravel 7.x and 8.x

    On Laravel 7 (or 8) wrap your code that throws events as per below:

    $user = User::withoutEvents(function () use () {
        $user = User::find(1);
        $user->name = 'John';
        $user->save();
    
        return $user;
    });
    

    Laravel 7.x docs
    Laravel 8.x docs


    Solution for Laravel versions from 5.7 to 6.x

    The following solution works from the Laravel version 5.7 to 6.x, for older versions check the second part of the answer.

    In your model add the following function:

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

    Then to save without events proceed as follow:

    $user = User::find(1);
    $user->name = 'John';
    
    $user->saveWithoutEvents();
    

    For more info check the Laravel 6.x documentation


    Solution for Laravel 5.6 and older versions.

    In Laravel 5.6 (and previous versions) you can disable and enable again the event observer:

    // getting the dispatcher instance (needed to enable again the event observer later on)
    $dispatcher = YourModel::getEventDispatcher();
    
    // disabling the events
    YourModel::unsetEventDispatcher();
    
    // perform the operation you want
    $yourInstance->save();
    
    // enabling the event dispatcher
    YourModel::setEventDispatcher($dispatcher);
    

    For more info check the Laravel 5.6 documentation

提交回复
热议问题