Creating a Resourceful Delete Button in Laravel

Forms Routing Views

Committed to the LaraBrain by: wjgilmore (@wjgilmore) at October 19, 2015 2:33 pm

Learn how to create a delete button for removing records the RESTful way

Resourceful (RESTful) routing is in my mind one of Laravel's great strengths, encouraging PHP developers to employ a standardized approach for building CRUD (create, retrieve, update, delete) interfaces. In fact when you create a controller using Artisan, Laravel will by default create a Resourceful controller for you unless you explicitly pass the --plain option.

Once created it's pretty easy to implement each of the seven resourceful actions (index, create, store, show, edit, update, destroy), but in some cases wiring up your UI to execute these actions it isn't so straightforward. For instance, you can't just create a simple GET method link to the destroy method because this method will only respond to requests sent in conjunction with the DELETE method.

Making matters worse, not all browsers support the DELETE method, meaning Laravel uses a workaround to ensure RESTful controllers can nonetheless be implemented. It does so by requiring your to pass along a hidden form field called _method which specifies that the DELETE method is indeed intended. Therefore you'll actually need to create a form that acts like a link. This is easily done by creating a form containing just a single submit button, and additionally passing along the hidden _method field like so:

{{ Form::open(
    'route' => ['tip.destroy', $tip->id], 
    'class' => 'pull-right'
) }}
{{ Form::hidden('_method', 'DELETE') }}
{{ Form::submit('Delete this Tip', 
    'class' => 'btn btn-warning'
{{ Form::close() }}

Once the Delete this Tip button is clicked, the Tip controller's destroy method will be executed and the tip ID passed along. The destroy method's implementation is easy; just call the Tip model's destroy method.