Created
March 2, 2020 16:06
-
-
Save casperwilkes/10a2bee6b9e94dd4a663d7cb0e4ae3ff to your computer and use it in GitHub Desktop.
Laravel override trait for soft deletes that recognizes the observer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Overrides original SoftDeletes::runSoftDelete method to include observer changes in `deleting` event. | |
* @see SoftDeletes | |
* @uses SoftDeletes::runSoftDelete() | |
*/ | |
namespace App\Traits; | |
use Illuminate\Database\Eloquent\SoftDeletes; | |
/** | |
* Trait SoftDeletesTrait | |
* @package App\Traits | |
*/ | |
trait SoftDeletesTrait { | |
use SoftDeletes; | |
/** | |
* Perform the actual delete query on this model instance. | |
* Parent method in softDeletes trait | |
* @return void | |
*/ | |
protected function runSoftDelete(): void { | |
$query = $this->setKeysForSaveQuery($this->newModelQuery()); | |
$time = $this->freshTimestamp(); | |
$columns = [$this->getDeletedAtColumn() => $this->fromDateTime($time)]; | |
$this->{$this->getDeletedAtColumn()} = $time; | |
if ($this->timestamps && !is_null($this->getUpdatedAtColumn())) { | |
$this->{$this->getUpdatedAtColumn()} = $time; | |
$columns[$this->getUpdatedAtColumn()] = $this->fromDateTime($time); | |
} | |
/** | |
* Add changes from observer here, | |
* overrides $columns, but leaves timestamps in tact | |
*/ | |
$columns = array_merge($query->getModel()->getDirty(), $columns); | |
/** | |
* Add attribute setting here | |
*/ | |
$query->update($columns); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Laravel didn't offer a way use the 'deleting' observer correctly when using soft deletes. This solution will grab any changes made in the observer, merge them with the timestamps created for the soft delete, and update the model with all changes.