Skip to content

Instantly share code, notes, and snippets.

@danpalmieri
Last active July 1, 2020 17:07
Show Gist options
  • Save danpalmieri/7f30686220db77091fa565df638252bb to your computer and use it in GitHub Desktop.
Save danpalmieri/7f30686220db77091fa565df638252bb to your computer and use it in GitHub Desktop.
A Laravel Trait to Allow temporarily disable timestamps update's.
<?php
namespace App\Traits;
use Illuminate\Database\Eloquent\Model;
trait CanIgnoreTimestamps
{
protected static $ignoreTimestamps = false;
public static function ignoreTimestamps(bool $ignore = true)
{
static::$ignoreTimestamps = $ignore;
}
public function usesTimestamps()
{
return parent::usesTimestamps() && !static::$ignoreTimestamps;
}
}
@danpalmieri
Copy link
Author

danpalmieri commented Jul 1, 2020

And then...

Set flag:
MyModel::ignoreTimestamps();

Do your stuff:
MyModel::(...)

Reset the flag:
MyModel::ignoreTimestamps(false);

The $timestamps property in the model is not static so you can't use that,
but Laravel always checks the usesTimestamps() method before setting the timestamps.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment