Laravel 9 SweetAlert2 with AJAX Example Tutorial

In this tutorial we are going to share how to use sweetalert in laravel 9 using ajax to showing the success message, delete message, and warning massage. Most of the time we need to sweet alert confirmation box with cancel and yes before delete or any else the data.

We already explain Delete Record with SweetAlert in Laravel Get or Post Method in previous example but here we will use with ajax. But follow the following steps sweet alert example of delete record in laravel 9 using ajax and jquery.

Step 1: Add Routes

First we need to add routes in routes/web.php file, One for getting all users and another is for deleting a single row data.

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;

Route::get('users', [UserController::class, 'index']);
Route::post('users/delete/{id}', [UserController::class, 'destroy']);

Step 2: Create Controller

Now here we have create a “UserController” and added two methods heree. One for getting all users and another for deleting a user, See hows they looks like:

app\Http\Controllers\UserController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;

class UserController extends Controller
{
    public function index()
    {
        $users = User::all();
        return view('users', compact('users'));
    }

    public function destroy($id)
    {
        $user = User::find($id);
        $user->delete();
        return response()->json([
            'success' => true,
            'message' => 'User successfully deleted',
        ]);
    }
}

Step 3: Apply SweetAlert2 with AJAX in Blade

Now here you need to create a view named “users.blade.php” and paste this code:

resources\views\users.blade.php

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha2/css/bootstrap.min.css">
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/10.5.1/sweetalert2.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/10.5.1/sweetalert2.all.min.js"></script>
    <title>How to Use SweetAlert2 with AJAX in Laravel 8</title>
</head>
<body class="container">

<div class="row">
    <div class="col-lg-12 margin-tb">
        <div class="pull-left">
            <h3>Users</h3>
        </div>
    </div>
</div>

<table class="table table-bordered">
    <tr>
        <th>ID</th>
        <th>Name</th>
        <th>Email</th>
        <th width="280px">Actions</th>
    </tr>
    @foreach ($users as $user)
        <tr>
            <td>{{ $user->id }}</td>
            <td>{{ $user->name }}</td>
            <td>{{ $user->email }}</td>
            <td>
                <button class="btn btn-danger" onclick="deleteConfirmation({{$user->id}})">Delete</button>
            </td>
        </tr>
    @endforeach
</table>

<script type="text/javascript">
    function deleteConfirmation(id) {
        swal.fire({
            title: "Delete?",
            icon: 'question',
            text: "Please ensure and then confirm!",
            type: "warning",
            showCancelButton: !0,
            confirmButtonText: "Yes, delete it!",
            cancelButtonText: "No, cancel!",
            reverseButtons: !0
        }).then(function (e) {

            if (e.value === true) {
                let token = $('meta[name="csrf-token"]').attr('content');
                let _url = `/users/delete/${id}`;

                $.ajax({
                    type: 'POST',
                    url: _url,
                    data: {_token: token},
                    success: function (resp) {
                        if (resp.success) {
                            swal.fire("Done!", resp.message, "success");
                            location.reload();
                        } else {
                            swal.fire("Error!", 'Sumething went wrong.', "error");
                        }
                    },
                    error: function (resp) {
                        swal.fire("Error!", 'Sumething went wrong.', "error");
                    }
                });

            } else {
                e.dismiss;
            }

        }, function (dismiss) {
            return false;
        })
    }
</script>
</body>
</html>

Step 4: Generate Fake Data

Here you can generate fake users for testing bases, For faker records please visite following links, where you can lean step by step how to generate fake data using seeder or laravel faker and factory.

Step 5: Run and See Output

Now run the Laravel project and visit this route. All users showing and delete any one you will see a sweetalert confirmation before deleting any records.

http://localhost:8000/users

I hope this will work for you.

Leave a Comment