Code your dreams into reality.
Every line of code is a step towards a better future.
Embrace the bugs, they make you a better debugger.

Laravel 11 SweetAlert Tutorial

Last Updated on June 23, 2024 by

SweetAlert or SweetAlert2 is a js library that allows developers to use sweetalert’s cdn on html pages and display popup messages like success, alert, error, warning to the users.

Let’s start the implementation to display a popup message on a blade view file using the sweetalert js library in laravel 11 applications:

Step 1 – Define Routes

Edit the routes/web.php file, and define routes in it to handle requests with controller:

<?php

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


Route::get('/list', [SweetAlertController::class, 'index']);
Route::post('/list/{id}', [SweetAlertController::class, 'removeData'])->name('list.removeData');

Step 2 – Create Controller

Run the following command to create a controller class to handle business logic in it:

php artisan make:controller SweetAlertController

Edit the app/Http/Controllers/SweetAlertController.php file, and in it implement the method for deleting the record along with showing the list and displaying the message on the view:

<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;

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

    public function removeData(Request $request,$id)
    {
      User::where('id',$id)->delete();
      return back();
    }
}

Step 3 – Create Blade File

Go to resources/views directory and create list.blade.php file, and then add the following code in it:

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 11 Sweet Alert Message Tutorial - Itcodstuff.com</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
    <meta name="csrf-token" content="{{ csrf_token() }}">
</head>
<body class="bg-light">
    <div class="container mt-5">
    <h2 class="mb-3">Laravel 11 Sweet Alert Message Example - Itcodstuff.com</h2>
    <table class="table">
        <tr>
            <td>Name</td>
            <td>Email</td>
            <td>Action</td>
        </tr>
        @foreach($users as $user)
            <tr>
                <td>{{$user->name}}</td>  
                <td>{{$user->email}}</td>  
                <td>
                    <button class="btn btn-outline-danger btn-sm delete-data" data-id="{{ $user->id }}" data-action="{{ route('list.removeData',$user->id) }}">Delete</button>
                </td>  
            </tr>
        @endforeach
    </table>
          
    </div>
</body>
</html>

Step 4 – Add SweetAlert CDN

Edit list.blade.php file, and sweetalert cdn in it:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/sweetalert2.all.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/sweetalert2.min.css" rel="stylesheet">

Step 5 – Use SweetAlert

Use the sweetalert methods on the blade view file to show the message to the users:

    <script type="text/javascript">
        $("body").on("click"," .delete-data", function(){
            var current_object = $(this);
            swal.fire({
                title: "Are you sure?",
                text: "We are going to delete this user forever.",
                type: "error",
                showCancelButton: true,
                dangerMode: true,
                cancelButtonClass: 'red',
                confirmButtonColor: 'blue',
                confirmButtonText: 'Delete',
            },function (result) {
                if (result) {
                    var action = current_object.attr('data-action');
                    var token = jQuery('meta[name="csrf-token"]').attr('content');
                    var id = current_object.attr('data-id');
                }
            });
        });
    </script>

Step 6 – Test This Application

Run the following command to start application server:

php artisan serve

Type http://localhost:8000/list url on browser to test this application.

Leave a Comment