MODAL DELETE IN LARAVEL
Hello Guys!
In this article, we’ll demonstrate how to implement a delete modal in Laravel. Before deleting a record, a modal will appear to confirm or cancel the action. Let’s get started!
This same content is also available in video format. You can watch it here 👇🏽
and the modal code is available on GitHub 👇🏽
https://github.com/mauriciocoelho/coffewithlaravel/blob/modal-delete/delete.blade.php
- Creating the Modal File
First, create the file responsible for the delete modal. I recommend organizing your code into directories. For example:
- For users: Create a modal directory inside the users folder and save the file as delete.blade.php.
- For other contexts (like products): Create the modal directory inside the corresponding folder, such as products/modal.
This helps keep your project well-structured.
- Structuring the Modal
After creating the file, add the following code to set up the modal:
<form action="{{ route('users.destroy', $user->id) }}" method="post" enctype="multipart/form-data">
{{ method_field('delete') }}
{{ csrf_field() }}
<div class="modal fade text-left" id="ModalDelete{{$user->id}}" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">{{ __('Delete User') }}</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">You sure want to delete <b>{{$user->id}}</b>?</div>
<div class="modal-footer">
<button type="button" class="btn gray btn-outline-secondary" data-dismiss="modal">{{ __('Cancel') }}</button>
<button type="submit" class="btn btn-outline-danger" data-dismiss="modal">{{ __('Delete') }}</button>
</div>
</div>
</div>
</div>
</form>
- Calling the Modal in the Listing
In the table listing, add the button to trigger the modal inside the corresponding <td>:
<a class="btn btn-danger" href="#" data-toggle="modal" data-target="#ModalDelete{{$user->id}}">
{{ __('Delete') }}
</a>
And outside the <td>, include the modal file to ensure it’s loaded correctly:
@include(‘user.modal.delete’)
Now, clicking the delete button will open the modal, featuring fully functional ‘Cancel’ and ‘Delete’ buttons.