Docs / Building
Soft Deletes
hide deleted rows, and mark rows deleted instead of removing them.
Introduction #
A soft-deleted row stays in its table, with the time it was deleted in a column such as deleted_at. In Laravel for PHP, a model with the SoftDeletes trait works this way, and Restify for PHP hides those rows from every request.
The framework has no soft deletes of its own, so a repository declares the column, and Restify does the rest.
Turning soft deletes on #
Give the model a nullable timestamp column, then return it from soft_deletes. This is the example app's PostRepository:
use laravel::model::Column;
use laravel::time::Timestamp;
impl Repository for PostRepository {
// ...
/// Deleted posts stay in the table with a `deleted_at`, and no request reaches them.
fn soft_deletes() -> Option<Column<Post, Option<Timestamp>>> {
Some(Post::deleted_at)
}
}
The migration adds the column with table.soft_deletes().
What changes #
With the column declared:
- Every request leaves out the rows where the column is set. The list doesn't show them. Show, update, delete, actions and getters answer
404for them, as for a row that doesn't exist. The MCP tools do the same. DELETE /api/restify/posts/{id}answers204as before, but setsdeleted_atto now instead of removing the row. It is an update, soupdated_atchanges too, as in PHP. The model'sUpdatedevent fires, notDeleted, and the repository'sdeletedhook still runs.Repository::queryreceives the query with the deleted rows already left out.
Without the column, a delete removes the row.
Relationships on other models #
soft_deletes covers the queries Restify runs for the repository. A relationship declared on another model, such as User::posts, is loaded by the framework and doesn't pass through the repository. In PHP, Eloquent left the deleted rows out of those too. Give the relationship a filter to do the same, as the example app's User model does:
/// The user's posts, without the soft-deleted ones, as Eloquent's `SoftDeletes` leaves them
/// out of PHP's `$user->posts`.
#[has_many(filter = Post::deleted_at.is_null())]
pub posts: HasMany<Post>,
Without the filter, ?related=posts would show deleted posts. Your own code outside Restify also sees deleted rows unless it filters them.
What isn't served #
Restify for PHP has no route that lists, restores or permanently deletes a soft-deleted row, so neither does this crate. Write your own route if you need one.