Home / Snippets / Saving A Single Model Without Events in Laravel 8
Saving A Single Model Without Events in Laravel 8 cover

Saving A Single Model Without Events in Laravel 8

3.4K

3 years ago

0 comments

Sometimes you may need to "save" a given model without dispatching any events in Laravel. You may accomplish this using the "saveQuietly" method instead of the normal "save" method.

saveQuietly Laravel 8

<?php

$article = Article::findOrFail(1);

$article->title = 'Article Number 1';

$article->saveQuietly();
By using "saveQuietly" you can prevent "dispatching event looping" which when if the Article model for this example has "$dispatchesEvents" property and it keeps on firing the same event over and over again.
<?php

/**
 * The event map for the model.
 *
 * @var array
 */
protected $dispatchesEvents = [
    'updated' => ArticleSaved::class,
    'saved' => ArticleSaved::class,
];
Do note that this feature is only available in Laravel 8 to work.

withoutEvents Laravel 7/8


For older Laravel versions you can make use of the "withoutEvents" static method like below.
<?php

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

    return $user;
});
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

If you like our tutorial, support us by being our Patreon or buy us some coffee ☕️

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this