Home / Snippets / Laravel Update Model Quitely
Laravel Update Model Quitely cover

Laravel Update Model Quitely

2.4K

3 years ago

0 comments

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