Ukieweb

Diary

I write what I learn here

Laravel Soft Delete Feature

Laravel Soft Delete Feature

Sometimes you want to delete a record from your application but still have it in your database in case you want to refer to it in the future. How do you achieve this with ease?

Laravel provides a** Soft Deleting feature** using **Eloquent **that is effective and easy to implement. On high level, a deleted_at column that is _nullable _is included in your table and is updated when a user deletes a record. This feature is useful in tracking the records that are getting deleted because you can even view them separately.

In this post I describe the process of implementing Soft Delete in your application, I assume you have basic knowledge of Laravel CRUD operations as well as migrations.

  1. Include a _deleted_at _colum in your table. In case you are using migration add $table->softDeletes();preferably after $table->timestamps();. If you created your table manually add a _deleted_at _column and make it nullable by default.

  2. In your model, include use IlluminateDatabaseEloquentSoftDeletes; and use SoftDeletes; inside the class. You can also include protected $dates = ['deleted_at']; to indicate that the attribute should be mutated to dates. When you create a new record, the deleted_at column is null by default.

  3. To delete a record use Post:: where('id',$id)->delete();. This will create a timestampon the deleted_at column.

  4. Eloquent removes all the records that have been deleted from the query by default. Such as using Post::all();. In case you are using Query Builder include ->whereNull('deleted_at')in the query to fetch undeleted records .

There exists other cool methods such as Post::withTrashed(); which returns all the records including the deleted ones. Post::onlyTrashed(); retrieves soft deleted records.

Another cool functionality is the ability to restore deleted records using Post::withTrashed() ->restore();. To delete a record completely use Post:: where('id',$id)->forceDelete();.

I hope you found this interesting and useful for your project.Happy coding!

0 Comments

To make a comment you have to login