Skip to content

Add soft deletes to models - #387

Open
kdrmlhcn wants to merge 2 commits into
laravel:0.xfrom
kdrmlhcn:soft-deletes
Open

kdrmlhcn wants to merge 2 commits into
laravel:0.xfrom
kdrmlhcn:soft-deletes

Conversation

@kdrmlhcn

@kdrmlhcn kdrmlhcn commented Dec 1, 2026 •

Copy link
Copy Markdown

Soft deletes are one of the most widely used Eloquent features, and #217 notes they were planned for a later slice of laravel::model. This PR adds them, following the shape of the existing model API as closely as possible. If you already have a different design in mind, please feel free to close this. I'm happy to rework it in whatever direction you prefer.

#[model(soft_deletes)]
pub struct Post {
    pub id: i64,
    pub title: String,
    pub deleted_at: Option<Timestamp>,
}

post.delete().await?;                                   // sets `deleted_at`
Post::query().get().await?;                             // leaves out soft-deleted rows
Post::query().with_trashed().get().await?;              // includes them
Post::query().only_trashed().get().await?;              // only them

let mut post = Post::query().only_trashed().find_or_fail(id).await?;
post.trashed();                                         // true
post.restore().await?;                                  // runs `restoring`, dispatches `Restored`
post.force_delete().await?;                             // removes the row

The behavior follows SoftDeletes and SoftDeletingScope on Laravel 13.x.

What changes

  • #[model(soft_deletes)] is opt-in, so models without it behave exactly as before. It requires a deleted_at: Option<Timestamp> field (a compile error says so otherwise), and it implements a new SoftDeletes marker trait. with_trashed, only_trashed, and the query restore / force_delete are only available on Builder<M: SoftDeletes>, so calling them on a model without soft deletes fails to compile, with an on_unimplemented hint.
  • The scope is applied once, in __query::<M>(). Every model query goes through it, so relationship queries, eager loads, with_count and other aggregates, has filters, and route model binding all leave out trashed rows without touching each relation type. The condition is table-qualified (posts.deleted_at is null), so it stays unambiguous in joins. Self-relation subqueries alias the table through the existing Requalify pass, which should rewrite the qualified column too, but that path isn't covered by a dedicated test yet.
  • with_trashed removes the scope by recognizing a private marker carried in the condition's existing ConditionKind::Typed slot. No new ConditionKind variant or compiler change was needed.
  • Instance writes and reloads always reach the row. query_of (used by update!, save, refresh, fresh, and delete) drops the scope, matching Eloquent's newQueryWithoutScopes behavior.
  • delete on a soft-deleting model, and on its queries, sets deleted_at and updated_at. On a model instance, both fields are also updated in memory with the same timestamp written to the row, as in Eloquent's runSoftDelete. It still runs deleting and dispatches Deleted, and the event's model reports trashed() == true.
  • restore clears deleted_at and touches updated_at in the database and on the model. It runs a new Hooks::restoring hook, which has a default no-op body so existing Hooks impls are unaffected, and dispatches a new Restored<M> event. A query's restore includes trashed rows, as Eloquent's does.
  • force_delete on a model runs deleting and dispatches Deleted. On a query it ignores the scope and also removes matching rows that are already trashed, matching Eloquent's Builder::forceDelete(), which calls $this->query->delete() on the base query without global scopes (unchanged in 13.x).
  • Meta gains deleted_at: Option<SoftDelete<M>>. #[model] is its only constructor in the codebase.

Docs

docs/models.md gains a "Soft deleting" section with "Querying soft-deleted models" and "Restoring and permanently deleting" subsections. The hooks table gains restoring, the events section names Restored<M>, and the "Which writes run hooks and events" table covers restore and force_delete. The #[model] options table documents soft_deletes.

Tests

tests/model_soft_deletes.rs adds 8 SQLite integration tests covering:

  • the soft delete itself, find, counts, and updated_at
  • with_trashed and only_trashed
  • restore, including a restoring hook that rejects the restore
  • force_delete on models and on queries
  • query delete, restore, and force_delete
  • has_many / belongs_to queries, with, with_count, has, and a with_count constrained with with_trashed
  • a join where both tables have deleted_at
  • updating and refreshing a trashed model
  • pruning trashed rows by age, mirroring the docs example

The full database suite passes locally, except schema_dump_writes_the_sqlite_schema_with_the_migrations_rows, which also fails on 0.x on my machine (macOS system sqlite3) and is unrelated to this change.

Not included

These felt better as follow-ups, to keep this PR reviewable:

  • assert_soft_deleted / assert_not_soft_deleted testing assertions (Add the testing assertions Laravel developers expect #266 mentions these as waiting on soft deletes)
  • with_trashed on route bindings
  • a force_deleting flag on Deleted or a separate ForceDeleted event
  • a prunable-style integration

Add #[model(soft_deletes)], which makes delete set a deleted_at column
instead of removing the row. Model queries, relationship queries, eager
loads, counts, and has filters leave out soft-deleted rows, and
with_trashed and only_trashed opt back in.

Models gain trashed, restore, and force_delete, and model queries gain
restore and force_delete. restore runs a new restoring hook and
dispatches a Restored event.
Keep the model's updated_at in step with the row when soft deleting
and restoring, as Eloquent's runSoftDelete and restore do, and let a
query's force_delete also remove trashed rows, as Eloquent's
Builder::forceDelete does.
@turgutahmet

Copy link
Copy Markdown

🚀

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants