Laravel Soft Deleting

How to use it?

  • When the delete method is called on the model, the deleted_at column will be set to current date and time.
  • When a model that uses soft deletes is queried, the soft deleted records will be automatically excluded in the query results. .

 

Various methods related to soft delete

  • trashed(): Determines if a model instance has been soft deleted

if ($flight->trashed()) {
//
}

  • withTrashed(): This method forces soft deleted records to appear in a result

$flights = App\Flight::withTrashed()
->where(‘account_id’, 1)
->get();

  • onlyTrashed(): This method will retrieve only soft deleted records

$flights = App\Flight::onlyTrashed()
->where(‘airline_id’, 1)
->get();

  • restore(): This un-deletes the soft deleted record i.e., restores the soft deleted record into ‘active’ state.

App\Flight::withTrashed()
->where(‘airline_id’, 1)
->restore();

  • forceDelete(): Permanently removes a soft deleted record.

 

Conclusion

Soft delete feature is a very useful feature of Laravel. This feature helps us to retrieve a record from database in case if a wrong record was deleted from the user interface. Implementing this is Laravel by following the above steps is really easy.

 

References

 

All search results