Posts Learn Components new Snippets new Categories Tags About
/

Laravel Update Model Quitely

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

Created on Sep 24, 2021

52 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!
new

If you like our tutorial, do make sure to support us with some coffee. We need the juice to write the content during the night 🤙🏻