Posts Learn Components Snippets Categories Tags Tools About
/

Laravel Update Model Quitely

Learn how to udpate model quietely in Laravel to prevent firing model event

Created on Sep 24, 2021

2325 views

Sometimes you might need to update a model without firing the model events in Laravel, to do that you can make use of the "withoutEvents" method available to each model instance. One of the implementations is to add a function from within the model class that will have this logic.

Laravel Update Quitely Code Example


Below is how you can define the method and it should be placed within any of the models that you want to update the data quietly.
<?php // app/Models/User.php

/**
 * Update the model without firing any model events
 *
 * @param array $attributes
 * @param array $options
 *
 * @return mixed
 */
public function updateQuietly(array $attributes = [], array $options = [])
{
    return static::withoutEvents(function () use ($attributes, $options) {
        return $this->update($attributes, $options);
    });
}

Extract Code to Trait


Since it's highly likely that you will make use of this method for most of your model then you can make a trait for that the model class can use. Below is how you can define the trait and it's recommended that you place it within the "app/Models/Trait" folder and have its own namespace.
<?php

namespace App\Models\Traits;

/**
 * @mixin \Eloquent
 */
trait CanSaveQuietly
{
    /**
     * Update the model without firing any model events
     *
     * @param array $attributes
     * @param array $options
     *
     * @return mixed
     */
    public function updateQuietly(array $attributes = [], array $options = [])
    {
        return static::withoutEvents(function () use ($attributes, $options) {
            return $this->update($attributes, $options);
        });
    }
}
Now that you have the model you can use the trait from anywhere within your model that wishes to have this ability.
<?php

// ...

class Post extends Model
{
    use CanSaveQuietly;

    // ...
}
If you found this snippet to be helpful do make sure to share it with your friends and cheers, happy coding!

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

Load comments for Laravel Update Model Quitely

new

PostSrc Code Components

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

View Components

Sponsors 👑

+ Add Yours
)