Skip to content

Instantly share code, notes, and snippets.

@casperwilkes
Created March 2, 2020 16:06
Show Gist options
  • Save casperwilkes/10a2bee6b9e94dd4a663d7cb0e4ae3ff to your computer and use it in GitHub Desktop.
Save casperwilkes/10a2bee6b9e94dd4a663d7cb0e4ae3ff to your computer and use it in GitHub Desktop.
Laravel override trait for soft deletes that recognizes the observer
<?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);
}
}
@casperwilkes
Copy link
Author

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.

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