Laravel Delete Confirmation Alert Dialog with Sweet Alert

In this tutorial, we going to share Laravel Delete Confirmation Alert Dialog with Sweet Alert. Deleting records with sweet alert confirmation is very important because not the data will delete any misunderstanding.

Sweet Alert offers an elegant solution to display confirmation dialogs to users, ensuring they have clarity and confidence when deleting records. By implementing the Sweet Alert confirmation box with cancel and yes buttons, users can confirm their intent before proceeding with the deletion process in Laravel 11. Laravel Delete with Sweetalert confirms Alert Dialog box tutorial is added by step by step process below.

This approach not only enhances user experience but also mitigates the risk of unintended deletions. With Sweet Alert, users can confidently manage their data, knowing they have control over the actions they take.

So let’s dive into this tutorial and learn how to integrate Sweet Alert’s delete confirmation dialog seamlessly into your Laravel application, adding an extra layer of user-friendly functionality and security.

Laravel Delete with Sweetalert Step-by-Step Process

Follow the step by step process for Laravel Delete with Sweetalert confirm Alert Dialog box.

Step 1: Download Laravel App

Before proceeding with the installation of Laravel 11, ensure that your system meets the following prerequisites:

  • Laravel 11 requires PHP version 8.2 or higher. You can verify your PHP version by running php -v in your terminal or command prompt. If you don’t have PHP 8.2 installed, you’ll need to upgrade your PHP version.
  • Laravel supports multiple database systems such as MySQL, PostgreSQL, SQLite, and SQL Server. In Laravel 11, they have predefined DB_CONNECTION=sqlite in the .env file, but if you are using MySQL, you will need to update it.

To install Laravel 11, run the following command in your terminal:

composer create-project laravel/laravel:^11.0 laravel-app

If you prefer to install Laravel based on your PHP version, use the following command:

composer create-project laravel/laravel laravel-app

Once the installation is complete, navigate to the project directory:

cd laravel-app

Step 2: Setup your Database

Next, open the .env file and add your database credentials such as db connection, db name, username equally important password:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db name
DB_USERNAME=db user name
DB_PASSWORD=db password

Step 3: Run Migration and Add Dummy Records

Now open your terminal and run the migrate command:

php artisan migrate

You can see in your database some tables are generated including the users table;

So now we need some dummy users for testing purposes, For fake records, we will use the Laravel faker here. you just need to run the below command on your terminal:

php artisan tinker
    
User::factory()->count(20)->create()

Step 4: Make Routes

Now, we will create two routes for implementing the delete records using sweetalert. One route is used for the users list and another is for deleting record.

So, open the routes/web.php file and update the below routes on it;

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\UserController;
  
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
  
Route::get('users', [UserController::class, 'index'])->name('users.index');
Route::delete('users/delete/{id}', [UserController::class, 'delete'])->name('users.delete');

Step 5: Create Controller and Update Logic

Now, we will create a UserController using the following command:

php artisan make:controller UserController

You can see in your app/http/controllers directory a new UserController will be generated here;

So, open the app/Http/Controllers/UserController.php file and update the following code on it;

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\User;
  
class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $users = User::paginate(20);
          
        return view('users', compact('users'));
    }
  
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function delete($id)
    {
        User::find($id)->delete();
  
        return back();
    }
}

Step 6: Create Blade File

Now we move to the last step, Here we will create a blade view file that will show the list of users, so we can see the delete records using the sweet alert package in laravel application.

So, create a new blade users.blade.php file inside the resources/views directory. Next, open the resources/views/users.blade.php file and add the below code on it;

<!DOCTYPE html>
<html>
<head>
    <title>Laravel App</title>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
      
<div class="container">
    <h1>Laravel Sweet Alert Confirm Delete Example</h1>
  
    <table class="table table-bordered data-table">
        <thead>
            <tr>
                <th>No</th>
                <th>Name</th>
                <th>Email</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
            @foreach($users as $user)
                <tr>
                    <td>{{ $user->id }}</td>
                    <td>{{ $user->name }}</td>
                    <td>{{ $user->email }}</td>
                    <td>
                        <a href="/users/delete/{{$user->id}}" class="btn btn-danger delete-confirm">Delete</a>
                    </td>
                </tr>
            @endforeach
        </tbody>
    </table>
</div>
    
</body>
  
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.0/sweetalert.min.js"></script>
<script type="text/javascript">
    $('.delete-confirm').on('click', function (e) {
        e.preventDefault();
        const url = $(this).attr('href');
        swal({
            title: 'Are you sure?',
            text: 'This record and it`s details will be permanantly deleted!',
            icon: 'warning',
            buttons: ["Cancel", "Yes!"],
        }).then(function(value) {
            if (value) {
                window.location.href = url;
            }
        });
    });
  
</script>
  
</html>

Step 7: Run the Application and Test

So, our Laravel delete records with sweet alert confirmation dialogue examples are added and now we need to test it. For this, we just need to run our application using the below command

php artisan serve

See the result here:

localhost:8000/users

I hope you are now perfectly know how to delete records in laravel with sweetalert.

Leave a Comment