Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
278 views
in Technique[技术] by (71.8m points)

Is it possible to temporarily disable event in Laravel?

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

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

so everytime the model is saved I can have a flash message to inform users. The problem is, sometimes I just need to update a field like 'status' or increment a 'counter' and I don't need a flash message for this. So, is it possible to temporarily disable triggering the model event? Or is there any Eloquent method like $model->save() that doesn't trigger 'saved' event?

question from:https://stackoverflow.com/questions/29407818/is-it-possible-to-temporarily-disable-event-in-laravel

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...