📅  最后修改于: 2023-12-03 14:43:46.138000             🧑  作者: Mango
In Laravel, the concept of soft deletes is used to mark records as "deleted" instead of removing them from the database. This allows you to retain data integrity and easily recover or restore deleted records if needed. Laravel provides built-in support for soft deletes, making it easier to implement this feature in your application.
Soft deletes in Laravel make use of the deleted_at
column in the database table. By default, this column is set to NULL
for active records and set to a timestamp when the record is soft deleted. When a record is deleted, it is not permanently removed from the database, but instead marked as deleted. This is useful for scenarios where you might want to keep a record's relationships intact even after deletion.
To enable soft deletes for a model in Laravel, you need to add the Illuminate\Database\Eloquent\SoftDeletes
trait to the model class. The trait provides the necessary methods and functionality to handle soft deletes.
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class YourModel extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at'];
// Your model's code...
}
By adding the use SoftDeletes
statement and the $dates
property, Laravel knows to treat the deleted_at
column as a date and automatically handle the soft delete functionality.
To soft delete a record, you can simply call the delete()
method on the model instance.
$record = YourModel::find(1);
$record->delete();
Laravel will set the deleted_at
column to the current timestamp, marking the record as deleted.
To retrieve soft deleted records, you can use the withTrashed()
method along with your query. This method ensures that soft deleted records are included in the query result.
$records = YourModel::withTrashed()->get();
This will fetch both active and soft deleted records.
If you need to restore a soft deleted record, you can call the restore()
method on the model instance.
$record = YourModel::withTrashed()->find(1);
$record->restore();
The restore()
method will set the deleted_at
column back to NULL
, effectively restoring the record.
If you want to permanently remove a soft deleted record from the database, you can call the forceDelete()
method on the model instance.
$record = YourModel::withTrashed()->find(1);
$record->forceDelete();
This will completely remove the record from the database, including its relationships.
Soft deletes in Laravel provide a convenient way to handle deletions while maintaining data integrity. By following the steps mentioned above, you can easily implement soft deletes in your Laravel application and make use of the built-in functionality provided by the framework.