📜  laravel withtrashed - PHP (1)

📅  最后修改于: 2023-12-03 15:02:35.822000             🧑  作者: Mango

Laravel withTrashed - PHP

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.

Enabling Soft Deletion

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.

Using withTrashed()

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.

Filtering by Trashed

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.

Restoring Soft-Deleted Records

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.

Conclusion

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.