Use SweetAlert2 with AJAX in Laravel

Published on May 1, 2019 2 min read

Today I am going to share how to use SweetAlert2 in Laravel with AJAX. This tutorial isn’t very beginners. That’s why I won’t share how to create a route, controller, views etc. I’m assuming that you know those. So let’s start.

Table of Contents

  1. Create Methods in Controller
  2. Define Route
  3. Apply SweetAlert2 with AJAX in Blade File
  4. Run and See Output

Step 1 : Create Methods in Controller

I’ve created a controller named “UserController”. In that controller, I’m going to create two methods. One for getting all users and another for deleting a user. My methods look like:

UserController.php
<?php

namespace App\Http\Controllers;

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

class UserController extends Controller
{

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

    public function delete($id)
    {
        $delete = User::where('id', $id)->delete();

        // check data deleted or not
        if ($delete == 1) {
            $success = true;
            $message = "User deleted successfully";
        } else {
            $success = true;
            $message = "User not found";
        }

        //  Return response
        return response()->json([
            'success' => $success,
            'message' => $message,
        ]);
    }
}

Step 2 : Define Route

Let’s register the routes for the two methods:

routes/web.php
<?php

Route::get('users', '[email protected]');
Route::post('delete/{id}', '[email protected]');

Step 3 : Apply SweetAlert2 with AJAX in Blade File

Create a view named “users.blade.php” and paste this code:

users.blade.php
<!doctype html>
<html lang="en">
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <!-- csrf-token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
          integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <!-- jquery -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
    <!-- SweetAlert2 -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/7.2.0/sweetalert2.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/7.2.0/sweetalert2.all.min.js"></script>

    <title>Use SweetAlert2 with AJAX in Laravel</title>
</head>
<body class="container" style="margin-top: 40px;">

<div class="row" style="margin-bottom: 20px;">
    <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({
            title: "Delete?",
            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) {
                var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');

                $.ajax({
                    type: 'POST',
                    url: "{{url('/delete')}}/" + id,
                    data: {_token: CSRF_TOKEN},
                    dataType: 'JSON',
                    success: function (results) {

                        if (results.success === true) {
                            swal("Done!", results.message, "success");
                        } else {
                            swal("Error!", results.message, "error");
                        }
                    }
                });

            } else {
                e.dismiss;
            }

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

In the file I’ve set on AJAX confirmation button click. Take a look at the code. I hope you can understand. If you face any problem, write to me.

Step 4 : Run and See Output

Now run the Laravel project and visit this route
http://localhost:8000/users. You will see a page like this:

Click the Delete button to see the SweetAlert2 confirmation box.

If you select Yes button, the data will be deleted via AJAX and you will see a confirmation message like this:

The tutorial is over. Thank you. 🙂

Author

Hey, I'm Md Obydullah. I build open-source projects and write on Laravel, Linux server, modern JavaScript and more on web development. If you enjoy my content, please consider supporting what I do!

Follow Buy me a coffeeBuy me a coffee

10 Replies to “Use SweetAlert2 with AJAX in Laravel”

      1. I have same issue. delete is not working:

        path_info
        /endproject/delete/14
        status_code
        404
        status_text
        Not Found
        format
        html
        content_type
        application/json
        request_query
        []
        request_request
        array:1 [▶]
        request_headers
        array:12 [▶]
        request_server
        array:29 [▶]
        request_cookies
        array:3 [▶]
        response_headers
        array:3 [▼
        “cache-control” => array:1 [▶]
        “date” => array:1 [▶]
        “content-type” => array:1 [▶]
        ]
        session_attributes
        []

Leave a Reply

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