Laravel Sweet Alert Confirm Delete with Example

February 3, 2023
Laravel
Laravel Sweet Alert Confirm Delete with Example

In this tutorial, you going to learn how to add the Sweet Delete Confirm Alert in laravel.

We will be discussing in detail how to install sweet alert in laravel and how to show sweet alert confirmation box when we press delete button.

This tutorial is valid for all other version of laravel, including laravel 7, laravel 8 and laravel 9 as well.

We will use the example of users and will implement sweet alert confirm delete popup on user delete button.

Lets get started!

Step 1: Install Laravel

The first step is going to be installing the laravel itself if you haven’t installed yet. I am installing in folder sweet_alert_delete_example. So open up the terminal and type the following command:

composer create-project --prefer-dist laravel/laravel sweet_alert_delete_example

Step 2: Migrate Tables

Since we will be using the users table as an example, we need to migrate the structure and tables. Type the following command in terminal:

php artisan migrate

This will how it look like:

Migrating tables in laravel

Step 3: Run the Application

Now you can run the application using the following command in the terminal:

php artisan serve

Keep the terminal open, to make the app running and open new terminal for making next commands in the separate terminal.

Step 4: Insert Dummy Users

Now to insert some dummy users, we will be using tinker and factory, if you don’t know about tinker it allows you to run PHP code in terminal and factory allows us to create dummy data. Here is following commands which you can type in the terminal in order to create 10 dummy users.

 php artisan tinker 

Then type to create 10 dummy users:

User::factory()->count(10)->create()

Step 5: Create Controller and Route

Now we need to create the controller in which we will create a function for viewing the users and delete function for delete user.

Type the following command in the terminal to create a controller:

php artisan make:controller UsersController

Now then go to the routes/web.php and add the following routes:

Route::get('users', [UsersController::class, 'index'])->name('users.index');
Route::delete('users/{id}', [UsersController::class, 'delete'])->name('users.delete');

This how the routes/web.php will look like

Creating Routes in Laravel

Step 6: Create delete function to delete the user

Now as mentioned earlier, we will create deletefunction in \App\Http\Controllers\UsersController for deleting the user. This how the delete function look like:

   public function delete($id)
    {
        User::find($id)->delete();
        return back();
    }

In the above code, the delete function getting passed the id of the user and which we are searching the database using find and then delete the user using delete() and then reloading the same page.

Step 7: Create Index function and views to Render Users Data

Now we will create index function in \App\Http\Controllers\UsersController for viewing the data of the users in which we will fetch data from the database and pass data to the view.

a) Create Index function

Type the following code in \App\Http\Controllers\UsersController file:

 public function index(){
        $users=User::get();
        return view('users',compact('users'));
    }

As you can see in the above code we are getting the data from User Model and then we are passing data to users view.

b) Create View file

Now we need to create the users.blade.php view file in resources\views, in which we will create table with bootstrap and jquery included. This how you do it:

<!DOCTYPE html>
<html>
<head>
    <title>Laravel Sweet Alert Confirm Delete with Example</title>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.2.3/css/bootstrap.min.css" integrity="sha512-SbiR/eusphKoMVVXysTKG/7VseWii+Y3FdHrt0EpKgpToZeemhqHeZeLWLhJutz/2ut2Vw1uQEj2MbRF+TVBUA==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.3/jquery.min.js" integrity="sha512-STof4xm1wgkfm7heWqFJVn58Hm3EtS31XFaagaa8VMReCXAkQnJZ+jEy8PCC/iT18dFy95WcExNHFTqLyp72eQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</head>
<body>

<div class="container mt-5">
    <h1>Laravel Sweet Alert Confirm Delete with Example</h1>

    <table class="pt-2 table table-bordered">
        <thead>
        <tr>
            <th>#</th>
            <th>Name</th>
            <th>Email</th>
            <th></th>
        </tr>
        </thead>
        <tbody>
        @foreach($users as $user)
            <tr>
                <td>{{ $user->id }}</td>
                <td>{{ $user->name }}</td>
                <td>{{ $user->email }}</td>
                <td>
                    <form method="POST" action="{{ route('users.delete', $user->id) }}">
                        @csrf
                        <input name="_method" type="hidden" value="DELETE">
                        <button type="submit" class="btn btn-danger confirm-button" >Delete</button>
                    </form>
                </td>
            </tr>
        @endforeach
        </tbody>
    </table>
</div>

</body>

This is how it will look like if you open the browser and type http://127.0.0.1:8000/users

Loading Users from the Database Laravel

C) Installing sweet alert and configure with delete button

Now before body closing tag, add the following code to install the sweet alert:

<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.0/sweetalert.min.js"></script>

Now add the following code to configure sweet alert with the the delete button:


<script type="text/javascript">

    $('.confirm-button').click(function(event) {
        var form =  $(this).closest("form");
        event.preventDefault();
        swal({
            title: `Are you sure you want to delete this row?`,
            text: "It will gone forevert",
            icon: "warning",
            buttons: true,
            dangerMode: true,
        })
            .then((willDelete) => {
                if (willDelete) {
                    form.submit();
                }
            });
    });

</script>

In the above code, on the click on delete button, we are preventing the delete button to submit the form using event.preventDefault() .

Then we using swal function which is sweet alert function to configure the settings in which we passing title and body text . Also using buttons: true configuration, the sweet alert will add the okay and cancel itself in the popup.

That okay and cancel button is linked with willDelete variable which is accessible in chain function then.

So if okay button will be pressed willDelete will be true and it will submit the form and calls the delete function we created before, which will delete the data. If cancel button is present, willDelete will be false and nothing will happen, except the popup confirmation will disappear.

This how it will confirmation popup look like if we press delete button:

Sweet Alert Conform Poup Delete Example

And if we press okay it will delete the data:

And if we press cancel nothing will happen. Thats it! You have successfully added, installed and configured sweet alert confirm delete popup in laravel.

Conclusion

Hope in the above article, you have learned today, how to add, install and configure sweet alert confirm delete popup in laravel. See you in the next one, peace.

Tags

Write a Reply or Comment

Your email address will not be published. Required fields are marked *


Icon