How to soft delete records in laravel and eloquent?

by cortez.connelly , in category: PHP Frameworks , 11 days ago

How to soft delete records in laravel and eloquent?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by samara , 10 days ago

@cortez.connelly 

Soft deleting records in Laravel and Eloquent involves using the SoftDeletes trait provided by Laravel. Here is a step-by-step guide on how to soft delete records in Laravel:

  1. Add a deleted_at column to your database table: If you haven't already, you need to add a deleted_at column to your database table. This column will be used to store the timestamp of when the record is soft deleted.
  2. Add the SoftDeletes trait to your Eloquent model: In your Eloquent model, use the SoftDeletes trait provided by Laravel. This trait adds the necessary methods to soft delete and restore records. use IlluminateDatabaseEloquentSoftDeletes; class YourModel extends Model { use SoftDeletes; }
  3. Soft delete a record: To soft delete a record, you can simply call the delete() method on the Eloquent model instance. $record = YourModel::find($id); $record->delete();
  4. Restore a soft deleted record: If you want to restore a soft deleted record, you can call the restore() method on the Eloquent model instance. $record->restore();
  5. Query soft deleted records: To query soft deleted records, you can use the withTrashed() method on a query builder instance. $records = YourModel::withTrashed()->get();
  6. Query only soft deleted records: If you want to query only soft deleted records, you can use the onlyTrashed() method on a query builder instance. $records = YourModel::onlyTrashed()->get();


By following these steps, you can implement soft deletion for records in Laravel and Eloquent. Soft deleting records can be useful in scenarios where you want to retain the data for potential recovery or auditing purposes.