DEV Community

loading...

How to implement Delete Confirmation in Laravel 8, 7,6 with Modal

kingsconsult profile image Kingsconsult Updated on ・6 min read

Hello devs, How are you doing? I am going to be showing you a little trick on how to implement delete confirmation using bootstrap modal.
In designing an application, we need to take into consideration that the user might not be that careful in using our application or unconsciously be pressing something on their phone or with the mouse and can accidentally click the delete button, so we need to make sure that in terms of delicate activities like deleting a data, there should be some level of confirmation, there are many ways to achieve this, you can use alert or confirm in JavaScript with jQuery, but we are going to be using bootstrap, this way it will look better and give us more chances of customizing how the confirmation will look.
Let's get into the business, We are going to be using the code from my previous article Laravel 8 CRUD App, A simple guide, the repo

Click on my profile to follow me to get more updates.

Step 1: Setup the app

  1. git clone https://github.com/Kingsconsult/laravel_8_crud.git
  2. cd laravel_8_crud/
  3. composer install
  4. npm install
  5. cp .env.example .env
  6. php artisan key:generate
  7. Add your database config in the .env file (you can check my articles on how to achieve that)
  8. php artisan migrate
  9. php artisan serve (if the server opens up, http://127.0.0.1:8000, then we are good to go) localhost
  10. Navigate to http://127.0.0.1:8000/projects

Step 2: add delete route

Laravel resources route provides us with seven (7) methods that handle the CRUD operation, which means we have the delete method called destroy method already created. But we are going to add a new route called delete, what this route will do is redirect us to the modal that will execute the destroy method. So add the code below before the resource route for project

Route::get('projects/delete/{id}', [ProjectController::class, 'delete'])->name('delete');
Enter fullscreen mode Exit fullscreen mode

web route

Step 3: Create delete method

In our route, we indicate that we have a delete method in the project controller, so we need to create that, go to app/Http/Controllers/ProjectController.php and add the following method

public function delete($id)
{
    $project = Project::find($id);

    return view('projects.delete', compact('project'));
}
Enter fullscreen mode Exit fullscreen mode

The delete function accepts an id, which is the id of the item we want to delete, and return the delete view in our projects directory along with the id of the item.

Step 4: Create Delete view

In our delete method, we return the delete view, so we need to create that, go to resources/views/projects/ and create a delete blade file delete.blade.php and copy the code below and paste.

{{-- !-- Delete Warning Modal -->  --}}
<form action="{{ route('projects.destroy', $project->id) }}" method="post">
    <div class="modal-body">
        @csrf
        @method('DELETE')
        <h5 class="text-center">Are you sure you want to delete {{ $project->name }} ?</h5>
    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
        <button type="submit" class="btn btn-danger">Yes, Delete Project</button>
    </div>
</form>
Enter fullscreen mode Exit fullscreen mode

From the code above, we need to pass an id to the destroy method, the id of the item to be deleted, we also customize the delete message, so that the user will be sure what to delete.
The form will be the modal that will display for confirmation before deleting, the submit button will be the button that will execute the deleting, while the button with type button will cancel the form which will not delete the item.

Step 5: Edit the index.blade.php

@extends('layouts.app')

@section('content')

<div class="row">
    <div class="col-lg-12 margin-tb">
        <div class="pull-left">
            <h2>Laravel 8 CRUD </h2>
        </div>
    </div>
</div>

<div class="pull-left ">
    <a class="btn btn-success" href="{{ route('projects.create') }}" title="Create a project"> <i class="fas fa-plus-circle"></i>
    </a>
</div>
<div class="d-flex">
    <div class="mx-auto">

        <form action="{{ route('projects.index') }}" method="GET" role="search">

            <div class="d-flex">

                <button class="btn btn-info t" type="submit" title="Search projects">
                    <span class="fas fa-search"></span>
                </button>
                <input type="text" class="form-control mr-2" name="term" placeholder="Search projects" id="term">
                <a href="{{ route('projects.index') }}" class="">
                    <button class="btn btn-danger" type="button" title="Refresh page">
                        <span class="fas fa-sync-alt"></span>
                    </button>

                </a>
            </div>
        </form>
    </div>
</div>

@if ($message = Session::get('success'))
<div class="alert alert-success">
    <p>{{ $message }}</p>
</div>
@endif

<table class="table table-bordered table-responsive table-hover">
    <thead class="thead-dark">
        <tr>
            <th scope="col">No</th>
            <th scope="col">Name</th>
            <th scope="col">Introduction</th>
            <th scope="col">Location</th>
            <th scope="col">Cost</th>
            <th scope="col">Date Created</th>
            <th scope="col">Action</th>
        </tr>
    </thead>
    <tbody>
        @foreach ($projects as $project)
        <tr>
            <td scope="row">{{ ++$i }}</td>
            <td>{{ $project->name }}</td>
            <td>{{ $project->introduction }}</td>
            <td>{{ $project->location }}</td>
            <td>{{ $project->cost }}</td>
            <td>{{ date_format($project->created_at, 'jS M Y') }}</td>
            <td>

                <a href="{{ route('projects.show', $project->id) }}" title="show">
                    <i class="fas fa-eye text-success  fa-lg"></i>
                </a>

                <a href="{{ route('projects.edit', $project->id) }}">
                    <i class="fas fa-edit  fa-lg"></i>

                </a>
                <a data-toggle="modal" id="smallButton" data-target="#smallModal" data-attr="{{ route('delete', $project->id) }}" title="Delete Project">
                    <i class="fas fa-trash text-danger  fa-lg"></i>
                </a>
            </td>
        </tr>
        @endforeach
    </tbody>

</table>

{!! $projects->links() !!}

<!-- small modal -->
<div class="modal fade" id="smallModal" tabindex="-1" role="dialog" aria-labelledby="smallModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-sm" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body" id="smallBody">
                <div>
                    <!-- the result to be displayed apply here -->
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    // display a modal (small modal)
    $(document).on('click', '#smallButton', function(event) {
        event.preventDefault();
        let href = $(this).attr('data-attr');
        $.ajax({
            url: href
            , beforeSend: function() {
                $('#loader').show();
            },
            // return the result
            success: function(result) {
                $('#smallModal').modal("show");
                $('#smallBody').html(result).show();
            }
            , complete: function() {
                $('#loader').hide();
            }
            , error: function(jqXHR, testStatus, error) {
                console.log(error);
                alert("Page " + href + " cannot open. Error:" + error);
                $('#loader').hide();
            }
            , timeout: 8000
        })
    });

</script>

@endsection
Enter fullscreen mode Exit fullscreen mode

For the explanation of how I implement the modal functionality above, visit my previous article How to create modal in Laravel 8 and Laravel 6/7 with AJax

Edit the base layout of our app to add the jquery, ajax and bootstrap needed, go to resources/views/layouts/app.blade.php, copy and paste the code below.

<html>

<head>
    <title>App Name - @yield('title')</title>

    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css"
        rel="stylesheet">

    <!-- Font Awesome JS -->
    <script defer src="https://use.fontawesome.com/releases/v5.0.13/js/solid.js"
        integrity="sha384-tzzSw1/Vo+0N5UhStP3bvwWPq+uvzCMfrN1fEFe+xBmv1C/AtVX5K0uZtmcHitFZ" crossorigin="anonymous">
    </script>
    <script defer src="https://use.fontawesome.com/releases/v5.0.13/js/fontawesome.js"
        integrity="sha384-6OIrr52G08NpOFSZdxxz1xdNSndlD4vdcf/q2myIUVO0VsqaGHJsB0RaBE01VTOY" crossorigin="anonymous">
    </script>

    <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">

    <link href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css' rel='stylesheet' type='text/css'>



  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js' type='text/javascript'></script>


    <style>
        .footer {
            position: fixed;
            left: 0;
            bottom: 0;
            width: 100%;
            background-color: #9C27B0;
            color: white;
            text-align: center;
        }

        body {
            background-color: #EDF7EF
        }

    </style>

</head>

<body>
    @section('sidebar')

    @show

    <div class="container">
        @yield('content')
    </div>
    <div class="text-center footer">

        <h4>The writer needs a job</h4>
        <h4>+234 806 605 6233</h4>
        <h4>kingsconsult001@gmail.com</h4>
        <h4>Github: www.github.com/kingsconsult</h4>

    </div>


</body>

</html>
Enter fullscreen mode Exit fullscreen mode

Testing
Restarting our server in case, it is not running and going to projects

php artisan serve

http://127.0.0.1:8000/projects , create some projects to test
projects index
Click on the trash icon to delete a project
delete modal

You can get the complete code from the Github repo.
Follow me for more of my articles, you can leave comments, suggestions, and reactions.
I am open to any vacancy as a PHP backend engineer, my strength is in the Laravel framework

click the link to view my profile and follow me

Visit my other posts

Discussion

pic
Editor guide