Dhurim Kelmendi

@dhkelmendi

Creating an archive on your application easily

Many times, you do not want to actually let the users delete an entity. Rather, you want to soft delete it, or archive it, so that users can find it in the `trash`. There are several ways you can achieve this, and let’s see how you can achieve it while working with the Laravel framework.

Without any specific framework/language in mind, you can implement this by adding a boolean column archived in the desired table, and then fetch rows based on the value of this column. Easy, right?

Now, if you are using the Laravel framework, it provides out of the box support for soft deletes(i.e. archive). First of all, you need to have a deleted_at column in your table. Then, you can use it by simply adding use Illuminate\Database\Eloquent\SoftDeletes; and then, inside the Model use SoftDeletes; which makes the model use the SoftDeletes trait, fetching all the helpers that it provides. Some of the helpers worth mentioning are withTrashed, onlyTrashed, which help you fetch all the rows, including the trashed ones, or only the trashed. By default, if none of the mentioned helpers are used in the query, it will only fetch the rows that are not trashed.

After using the trait, you need to define a route, a controller method, and a view for displaying the archive. This is pretty straightforward, as you woud add Route::get('/entity_archive', 'EntityController@archive');. You can organize this part as you wish. Then, at the controller method, you should query the model, and remember to use onlyTrashed() like below.

archive method inside the EntityController.php

Now, you will be able to view only the archived rows from your entity. By default, when using $entity->delete();, Laravel will soft delete the entity row. It makes it possible to restore an archived row by running $archived_entity->restore();. If you want to delete permanently, you can run $entity->forceDelete();.

And that wraps it up. That's how easy it is.

Feel free to email me if you have any questions, challenging opportunities, or you just want to say hi.

Finally, be sure to follow me so that you do not miss any new stories I publish.

More by Dhurim Kelmendi

Topics of interest

More Related Stories