📅  最后修改于: 2023-12-03 15:02:35.822000             🧑  作者: Mango
Laravel withTrashed is a feature that allows you to access soft-deleted records in your database. Soft-deleted records are not removed from the database, but they are marked as deleted.
To enable soft deletion in your Laravel application, you need to add a deleted_at
column to your database table. You can do this by creating a migration file and adding the following code:
Schema::table('table_name', function (Blueprint $table) {
$table->softDeletes();
});
This will add a deleted_at
column to the table_name
table.
Once you have enabled soft deletion, you can use the withTrashed()
method to retrieve all records, including the soft-deleted ones.
$users = User::withTrashed()->get();
This will return all the users in the database, including the soft-deleted ones.
You can also filter your queries by trashed records using the onlyTrashed()
and withoutTrashed()
methods.
$users = User::onlyTrashed()->get();
This will return only the soft-deleted users.
$users = User::withoutTrashed()->get();
This will return all the users except the soft-deleted ones.
You can restore soft-deleted records using the restore()
method.
$user = User::withTrashed()->find(1);
$user->restore();
This will restore the soft-deleted user with an ID of 1.
Laravel withTrashed is a powerful feature that allows you to keep track of soft-deleted records in your database. With this feature, you can make your application more efficient and organized.