diff --git a/src/Traits/DetectsChanges.php b/src/Traits/DetectsChanges.php index 782dda17..05916ba1 100644 --- a/src/Traits/DetectsChanges.php +++ b/src/Traits/DetectsChanges.php @@ -53,7 +53,8 @@ public function attributeValuesToBeLogged(string $processingEvent): array return []; } - $properties['attributes'] = static::logChanges($this->exists ? $this->fresh() : $this); + $tmp = $this; + $properties['attributes'] = static::logChanges($this->exists ? $tmp->fresh() ?? $this : $this); if (static::eventsToBeRecorded()->contains('updated') && $processingEvent == 'updated') { $nullProperties = array_fill_keys(array_keys($properties['attributes']), null); diff --git a/tests/DetectsChangesTest.php b/tests/DetectsChangesTest.php index 11cf4fbf..1989bfa4 100644 --- a/tests/DetectsChangesTest.php +++ b/tests/DetectsChangesTest.php @@ -6,6 +6,7 @@ use Spatie\Activitylog\Test\Models\User; use Spatie\Activitylog\Test\Models\Article; use Spatie\Activitylog\Traits\LogsActivity; +use Illuminate\Database\Eloquent\SoftDeletes; class DetectsChangesTest extends TestCase { @@ -266,6 +267,46 @@ public function it_will_store_the_values_when_deleting_the_model() $this->assertEquals($expectedChanges, $this->getLastActivity()->changes()); } + /** @test */ + public function it_will_store_the_values_when_deleting_the_model_with_softdeletes() + { + $articleClass = new class() extends Article { + public static $logAttributes = ['name', 'text']; + + use LogsActivity, SoftDeletes; + }; + + $article = new $articleClass(); + $article->name = 'my name'; + $article->save(); + + $article->delete(); + + $expectedChanges = collect([ + 'attributes' => [ + 'name' => 'my name', + 'text' => null, + ], + ]); + + $this->assertEquals('deleted', $this->getLastActivity()->description); + $this->assertEquals($expectedChanges, $this->getLastActivity()->changes()); + + $article->forceDelete(); + + $expectedChanges = collect([ + 'attributes' => [ + 'name' => 'my name', + ], + ]); + + $activities = $article->activity; + + $this->assertCount(3, $activities); + $this->assertEquals('deleted', $this->getLastActivity()->description); + $this->assertEquals($expectedChanges, $this->getLastActivity()->changes()); + } + /** @test */ public function it_can_store_the_changes_of_array_casted_properties() { diff --git a/tests/LogsActivityTest.php b/tests/LogsActivityTest.php index 891a7dd8..bc7c8b0f 100644 --- a/tests/LogsActivityTest.php +++ b/tests/LogsActivityTest.php @@ -121,6 +121,13 @@ public function it_will_log_the_deletion_of_a_model_with_softdeletes() $this->assertEquals(get_class($this->article), $this->getLastActivity()->subject_type); $this->assertEquals($article->id, $this->getLastActivity()->subject_id); $this->assertEquals('deleted', $this->getLastActivity()->description); + + $article->forceDelete(); + + $this->assertCount(3, Activity::all()); + + $this->assertEquals('deleted', $this->getLastActivity()->description); + $this->assertNull($article->fresh()); } /** @test */