Laravel 5 Delete Records in your table, Beginner’s Guide

Deleting records in Laravel is very easy.

Since you can’t delete records via GET method (of course you can). No, you should not since if you use GET method in deleting a record, user might delete your records in the URL directly, and that’s a security problem.

Note: If you don’t want to entirely delete your record you can use SoftDeletes() in Laravel. See How to Soft Delete on Laravel 5

So, we have to pass on a POST method in the view to the controller. Doing this will allow the deletion to occur behind the scene.

This is the last part of the CRUD process, and you should know by now how to Create, Read and Update records. So I’m not going into details about the controller or model records.

To do this, in your index.blade.php (to wherever you want to put your delete button) we will add a new form. The form will contain our delete button, and will submit a POST data to our controller. I included an edit button also, just in case you needed some buttons beside you delete. Just make sure you put the added buttons inside the form. (I always use my own work, I used the Office as my sample model)

It seems a lot, but basically it just table and I added some Bootstrap class to it, some glyphicon to make it look nicer (you can remove it, if you want a simple delete button). I also added also nice bootstrap tooltip to make it even more cooler.

So, We created a form, inside our table. The method should be DELETE, which is specified in your route list. And the route should lead you to the destroy() function of your Controller. The form WILL SUBMIT THE ID of the record you want to delete.

We add a delete button type submit, and added a prompt to it by adding a JavaScript in onclick() attribute.

The above code will looked like this.

delete record

In your controller destroy() function add the following

The destroy() function accepts the ID the delete form passed. We find that ID in the model, and just delete it.

We added a nice flash message that will appear in the view to notify user about the deletion, then it will redirect back to the view. See Flash Messages in Laravel 5 for more info about Flash Messages.

Sharing is caring!