diff --git a/src/AuditableTraitObserver.php b/src/AuditableTraitObserver.php index b3bd09a..7eabbcf 100644 --- a/src/AuditableTraitObserver.php +++ b/src/AuditableTraitObserver.php @@ -58,7 +58,7 @@ public function saved(Model $model): void if (method_exists($model, 'getUpdatedByColumn')) { $updatedBy = $model->getUpdatedByColumn(); - if ($this->getAuthenticatedUserId() && $this->getAuthenticatedUserId() != $model->$updatedBy) { + if ($this->getAuthenticatedUserId() && $this->getAuthenticatedUserId() != $model->$updatedBy && $model->isDirty()) { $model->$updatedBy = $this->getAuthenticatedUserId(); $model->save(); } diff --git a/tests/Feature/AuditableModelTest.php b/tests/Feature/AuditableModelTest.php index 5e0dbeb..89f5c3d 100644 --- a/tests/Feature/AuditableModelTest.php +++ b/tests/Feature/AuditableModelTest.php @@ -47,3 +47,33 @@ expect($post->updated_by)->toBe($user->id); expect($post->deleted_by)->toBe($user->id); }); + +test('a model wont be updated if edited by another user without it being dirty', function () { + $user = User::create([ + 'name' => 'John Doe', + 'email' => 'john@example.com', + ]); + + actingAs($user); + + $anotherUser = User::create([ + 'name' => 'Jane Doe', + 'email' => 'jane@example.com', + ]); + + DB::table('posts')->insert([ + 'title' => 'Hello World', + 'created_by' => $anotherUser->id, + 'updated_by' => $anotherUser->id, + ]); + + $model = Post::first(); + + expect($model->created_by)->toBe($anotherUser->id); + expect($model->updated_by)->toBe($anotherUser->id); + + $model->save(); + + expect($model->created_by)->toBe($anotherUser->id); + expect($model->updated_by)->toBe($anotherUser->id); +});