Skip to content

fix: fixes issue #371 #34

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion src/Drivers/SoftDeleteDriver.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use InvalidArgumentException;
use RuntimeException;

class SoftDeleteDriver extends StandardDriver
{
Expand Down Expand Up @@ -81,11 +82,23 @@ public function persist(Model $model): bool
* @see https://github.com/cloudcreativity/laravel-json-api/issues/371
*/
if ($this->willSoftDelete($model)) {
assert(method_exists($model, 'getDeletedAtColumn'));
$column = $model->getDeletedAtColumn();
// save the original date so we can put it back later on.
$deletedAt = $model->{$column};
// delete the record so that deleting and deleted events get fired.
$model->delete();
$response = $model->delete(); // capture the response

// if a listener prevented the delete from happening, we need to throw as we are in an invalid state.
// developers should prevent this scenario from happening either through authorization or validation.
if ($response === false) {
throw new RuntimeException(sprintf(
'Failed to soft delete model - %s:%s',
$model::class,
$model->getKey(),
));
}

// apply the original date back before saving, so that we keep date provided by the client.
$model->{$column} = $deletedAt;
}
Expand Down
17 changes: 17 additions & 0 deletions tests/lib/Acceptance/SoftDeleteTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -332,6 +332,23 @@ public function testItDoesNotSoftDeleteOnUpdate(): void
]));
}

public function testItDoesNotSoftDeleteOnUpdateIfListenerReturnsFalse(): void
{
$post = Post::factory()->create(['deleted_at' => null]);

$data = ['deletedAt' => now()->toJSON(), 'title' => 'Hello World!'];

Post::deleting(fn() => false);

$this->expectException(\RuntimeException::class);
$this->expectExceptionMessage('Failed to soft delete model - App\Models\Post:' . $post->getKey());

$this->schema
->repository()
->update($post)
->store($data);
}

public function testItRestores(): void
{
$restored = false;
Expand Down