Laravel 5.8 Delete and soft delete (Practical examples)

Chrisostom Kaweza
6 min readApr 21, 2019

--

What is the sexiest job of the 21st century? Can you guess what? If you can’t, please go find the answer and come back….Ready? Let’s continue and I hope your answer includes data, if not please go do your homework.

In today’s world Data has become a very essential part of our lives. It is used in medical research to find the cure for diseases, for boosting company revenue or those targeted ads based on your online search history. Because of how crucial it is, Giant IT companies choose not to delete it. Instead, they soft delete it.

What is this article about?

In this article, I will be demonstrating to you how to soft delete data. I will be building a simple CRUD Laravel API application for this. You can always get the codes of this article from my Github repository here.

Who is this article for?

This article is for people who are new to the concept of soft deleting data, don’t understand how it’s done or how it works, and for those who would like to implement it in Laravel. Therefore, it’s for Laravel newbies and anyone else who might be interested in this topic.

What will you learn?

You will be learning the following:

You will learn how to permanently delete data.

What soft delete is about and how to soft delete.

How to retrieve soft deleted data, and how to retrieve a combination of soft deleted and non-soft deleted data.

Restoring soft deleted data, and permanently deleting a soft deleted model.

Tools, and working environment I will use

Text editor of your choice.

MySQL database.

Postman for testing APIs.If you don’t have download it here.

laravel working enviroment.

Enough with the talking lets get our hands dirty.

Setting up a laravel application, and a migration table.

Create new laravel app called noteapp

 laravel new noteapp

Then, set up a database in phpmyadmin. You can name it whatever you want. I will name mine noteapp. Don’t forget to set the environment variables in the .env file. Ready?…Good!.

Now, create a migration table called notes and a model called Note by running this command.

php artisan make:model Note –m

Set up your new migration table to look like this

Next, you should set up a new migration table. Migrate the table by running.

php artisan migrate

I believe you now have a table which looks like this.

Creating new notes

Go to app/routes/api.php and paste the following routes for all APIs.

Before we create new note go to NotesController copy and paste these two private functions; notFoundMessage which throw an error message when you hit an endpoint which does not exist, and successfulMessage which shows a successful message of an HTTP action.

To create a new note let’s create a method in NotesController called to create, which corresponds to the route.

Route::post(‘/v1/notes’, ‘NotesController@create’);

This is the corresponding method:

You can now test this by going to the postman and hitting the endpoint.

POST api//v1/notes  make sure the method in postman is POST

It will appear as follows

Fetch Notes

Create a method in NotesController called allNotes which corresponds to this route:

Route::get(‘/v1/notes’, ‘NotesController@allnotes’);
GET localhost:8000/api//v1/notes  GET method in postman to fetch the created post

Permanent delete notes

To permanently delete a resource, means to remove the resource from the database completely with no option for recovery.

There are several ways we can permanently delete a resource

  1. Delete a model by calling the delete method on the model instance
$note=Note::findorfail($id); // fetch the note$note->delete(); //delete the fetched note

2. Delete an existing model by key

However, if you know the ids, you can call the destroy method on the model instance

Model::destroy($id);

Hint if your expecting array of ids.

Your can delete it like Model::destroy([1,2,3]);

3. Delete model by query

Model::where(‘created_at’,<,date(‘Y-m-d’));

For this tutorial we are going to use the second delete method.

Create a method called permanentDelete which corresponds to the route below:

Route::delete(‘v1/notes/{id}’, ‘NotesController@permanentDelete’); //this on first permanent delete models

Here is the corresponding method

Test the endpoint in the API by passing the id of the note

DELETE localhost:8000/api/v1/notes/{id}     pass the id of note you wish to delete

Soft delete

When models are soft deleted, they are not actually removed from your database. Instead, a deleted_at attribute is set on the model and inserted into the database. If a model has a non-null deleted_at value, the model has been soft deleted.

Now, we are going to version our APIs because we are soft deleting instead of permanently deleting our data. This is considered as best practice. If any of this seems overwhelming to you, I would highly recommend that you check another article of mine: Writing standard RESTful API & nodejs (practical example).

(just don’t get cut up with the title it is applicable in every programming language).

Adding soft delete_at column on table

To add soft delete column in table, first add the following Line of code in your Note Model

Run the following command in your terminal

php artisan make:migration add_soft_deletes_to_notes_table — table=notes

Add this line your new migration file,then run

 php artisan migrate, 

column deleted_at is created in table notes.

soft deleting method

Basically, if you now hit the endpoint of the method permanentDelete above it will soft delete the notes since you specified that in Note model.

Now here is your homework. I need you to create a method called softDelete in NotesController, that has the same logic as the permanentDelete method above. It should corresponds to the below route

Route::delete(‘v2/notes/{id}’, ‘NotesController@softdelete’);

If it’s difficult, clone it from my Github repository here.

Hint: If you now fetch all notes by hitting the previous endpoint below, you will only get notes where delete_at is equal to null

GET localhost:8000/api/v1/notes  //now gives notes with null deleted_at

Fetching all notes which are not deleted, and soft deleted

This method will give us notes which are soft deleted and those which are not deleted at all.

create a method called notesWithSoftDelete in NotesConroller

This corresponds to the route

Route::get(‘v2/notes/withsoftdelete’,’NotesController@notesWithSoftDelete’);

To test this, go to the postman and hit the endpoint.

localhost:8000/api/v2/notes/withsoftDelete

Fetching only soft deleted notes

Sometimes you wish to get only soft deleted notes. Create method softDeleted, which implements the route

Route::get(‘v2/notes/softdeleted’,’NotesController@softDeleted’);

Here is the corresponding method.

To test the above method, got to the postman and hit the endpoint

GET localhost:8000/api/v2/notes/softdeleted

Restoring soft deleted notes

You may also want to restore soft deleted data. This could be in a scenario where your users want to restore their deleted data from the recycle bin.

Create a method called restore, which corresponds to this route:

Route::patch(‘/v1/notes/{id}’,’NotesController@restore’);

Here is the corresponding method

You can go to postman and test it.

PATCH localhost:8000/api/v1/notes/{id} id of soft deleted model

Permanent delete soft deleted notes

Sometimes, you may want to permanently delete the soft deleted notes. But his can cause a huge breaking change in the APIs implementation. In scenarios like these, you have to version your APIs.

To demonstrate this let’s create a method called permanentDeleteSoftDeleted in NotesController which corresponds to the following route

Route::delete(‘v3/notes/{id}’,’NotesController@permanentDeleteSoftDeleted’);

Here is the method for it.

You can go ahead and test it in postman by hitting the endpoint

DELETE localhost:8000/api/v3/notes/{id} //id of soft deleted model

Hint: you will get the source code in Github repo here

Wrap it Up

I know this was a long tutorial, but I believe it was worth it. Because if you never knew how to soft delete data before, now you do. You probably never worked with APIs but now you are able to create them. I hope this has helped anyone out there.

If you like the article please give a clap, for any query corresponding the article put them in section comment below. Otherwise, you can email me chrissoemma@gmail.com, check my twitter here, LinkedIn here.

Happy to give back to developers community.

BACKTODEVELOPERSCOMMUNITY(#BDC).

--

--