Laravel 5.4 #8 : Edit, delete and soft deletes

In this post, we will create the edit page, we will also give the possibility to delete posts to its creators and, finally, we will explain and use the soft deletes.


First, let’s create the posts editing page. Open the view  posts.blade.php  and add the link inside the loop that shows the posts. We are going to restrict that only the link can be viewed, if the user who created the post is the same one that is logged in.

Now we have to create the routes in the routes file. One route is the one that shows the view with the inputs (GET) and the other one (PATCH) is the one that updates the data:

We are giving the route a name because later we will use it in the edit form.

Once we have the routes, we have to create the methods to which the routes refer:

The first method (edit) what it does is according to the id that is passed, send the data to the view to show them in the inputs, if it doesn’t find any posts with that id, it shows an error.

The second method updates the post with the data sent from the inputs of the view and redirects to the list.

We need to create the edit view, we are going to create it, it will be called  post_edit.blade.php  and will contain:

If you notice, we are showing the form another way. We are doing it with the classes provided by the HTML & Forms package. We pass the $post variable so that it shows in the inputs the information that is in the database and will be sent to the route called posts.update with the id of the post through the HTTP PATCH method.

With this we could edit the posts, but there is problem when the title is not edited. In our validation we put the title has to be unique, then if it doesn’t change, it detects that it already exists and we will see an error. To solve this, we have to edit the PostRequest and change the title validation line:



We add this code below the edit link in the view:

Add the route:

Create the method in the controller:

And now the users can delete their posts.


We update the middlewares to restrict the access to some users (the ones aren’t logged in and those who aren’t creators of the post).

Note: this can be done in other ways that are better, (for example, with policies that we will deal with in the next post).


Soft delete

So they are permanently removed from the database, Laravel has a function that is very simple to add that avoids that. It simply marks them as deleted, but doesn’t delete the record. This is known as Soft delete.

First of all, like always when we have to modify the structure of the database, we must create a migration:

Open the file and add this:

Execute the migration:

When we have the field, simply, we have to add these lines to the model Post.php to activate soft deletes: