Posts Learn Components Snippets Categories Tags About
/

Saving A Single Model Without Events in Laravel 8

Learn how to save Model without triggering the event in Laravel 8

Created on Sep 05, 2021

25 views

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;
});

Snippets by

PostSrc poster

PostSrc

Full stack developer mainly focusing on the front end side of the web. The main author of PostSrc and loves writing tutorial and guides online.

new

PostSrc Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that's right for your project.

View Components

Other Code Snippets

More