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); }); } }
<?php // ... class Post extends Model { use CanSaveQuietly; // ... }
Leave a reply