Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel saving model without triggering events

Tags:

laravel

I am interested if there is a difference between saving the model using withoutEvents and saveQuietly. What is the main difference between next two pieces of code:

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

and:

$user = User::findOrFail(1);    
$user->name = 'Victoria Faith';    
$user->saveQuietly();
like image 552
nikname Avatar asked Mar 21 '21 17:03

nikname


People also ask

How do I get Started with events in Laravel?

Getting Started with Laravel Model Events 1 Events Overview. Eloquent has many events that you can hook into and add custom functionality to your models. ... 2 Registering Events. ... 3 Creating an Event Listener. ... 4 Trying out the Event Handler. ... 5 Stopping a Save. ... 6 Using Observers. ... 7 Learn More. ...

How do I conditionally dispatch an event in Laravel?

If you would like to conditionally dispatch an event, you may use the dispatchIf and dispatchUnless methods: When testing, it can be helpful to assert that certain events were dispatched without actually triggering their listeners. Laravel's built-in testing helpers makes it a cinch.

How do I register a closure based event listener in Laravel?

When registering closure based event listeners manually, you may wrap the listener closure within the Illuminate\Events\queueable function to instruct Laravel to execute the listener using the queue: * Register any other events for your application.

How many times can a listener be attempted in Laravel?

Therefore, Laravel provides various ways to specify how many times or for how long a listener may be attempted. You may define a $tries property on your listener class to specify how many times the listener may be attempted before it is considered to have failed: * The number of times the queued listener may be attempted.


1 Answers

SaveQuietly is a wrapper for the closure WithoutEvents that accepts options:

trait SaveQuietly
{
    /**
     * Save model without triggering observers on model
     */
    public function saveQuietly(array $options = [])
    {
        return static::withoutEvents(function () use ($options) {
            return $this->save($options);
        });
    }
}
like image 141
jeremykenedy Avatar answered Oct 21 '22 00:10

jeremykenedy