Home >PHP Framework >Laravel >How to implement soft delete in Laravel framework
Laravel is a powerful PHP framework that provides developers with many convenient functions. Among them, soft deletion is a very useful feature. This article will introduce how to implement soft deletion in the Laravel framework.
Soft deletion refers to marking a record as deleted rather than actually deleting the record. This gives us the opportunity to recover deleted records while maintaining data integrity. If we delete records directly, it may cause some dependencies, so soft deletion is a very good choice.
First, to enable soft deletions in Laravel, we need to use the SoftDeletes
feature in the model.
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class User extends Model { use SoftDeletes; protected $dates = ['deleted_at']; }
In the above example, we used use SoftDeletes
to enable soft deletions and defined a deleted_at
attribute which will be used in the model to save soft deletions Deletion timestamp.
Once we enable the SoftDeletes
feature, we can perform soft deletions using the delete()
method in Laravel. This method will set the deleted_at
attribute to the current timestamp. To restore a soft deleted record, we need to use the restore()
method in Laravel.
// 在模型中软删除一个记录 $user = User::find(1); $user->delete(); // 恢复一个软删除的记录 $user = User::withTrashed()->where('id', 1)->first(); $user->restore();
In the above code, we first soft delete a record using the delete()
method. We then use the withTrashed()
method to retrieve the soft deleted record and then use the restore()
method to restore the record.
When we retrieve data from a table, we typically do not want deleted records returned. Using Laravel's onlyTrashed()
method, we can list only deleted records. To list all records, including deleted records, use the withTrashed()
method.
// 获取只删除的记录 $deletedUsers = User::onlyTrashed()->get(); // 获取所有记录,包括已删除的记录 $allUsers = User::withTrashed()->get();
Laravel also provides a forceDelete()
method to forcefully delete soft-deleted records. This method will completely delete the record from the database, rather than simply setting the deleted_at
attribute to the current timestamp.
// 永久删除一个已删除记录 $user = User::withTrashed()->where('id', 1)->first(); $user->forceDelete();
In this article, we have learned how to enable and use soft delete in Laravel. Soft deletion improves our data integrity and helps us recover deleted records easily. In actual projects, soft deletion is a very useful function that we can use according to the needs of the project.
The above is the detailed content of How to implement soft delete in Laravel framework. For more information, please follow other related articles on the PHP Chinese website!