How to Show Notification using Sweet Alert in Laravel 10

Last Updated on by in Laravel

Alert notification is a type of communication between machine-to-human relative to the importance of the message.

In this sweet alert notification tutorial, you will learn how to comfortably use the sweet alert library to display an alert notification in the Laravel application.

We will also teach you how to integrate sweet alerts in Laravel and get users’ attention on the spot.

A sweet alert is a tiny package that helps you track how the user interacts with the alert. Sweet alert tends to offer greater flexibility, especially in customization.

You will discover how to use sweet alerts in laravel using the MVC pattern profoundly.

How to Implement and Use Sweet Alert in Laravel 10

  • Create Laravel Project
  • Add Database Details
  • Seed Users in Database
  • Create New Controller
  • Build View Template
  • Create New Routes
  • Run Development Server

Create Laravel Project

To display notification messages using alert, we must first build a brand new app.

You must install composer in your development system; you can run the given command then.

composer create-project laravel/laravel --prefer-dist laravel-demo
cd laravel-demo

Add Database Details

Since, we are storing users data in database. Therefore, we need to connect the SQL db with the laravel.

You can do it by adding your database information in .env file.

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=laravel_db
DB_USERNAME=root
DB_PASSWORD=

For macOS MAMP PHP server; make sure to additionally include UNIX_SOCKET and DB_SOCKET right below the database details in .env file.

UNIX_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock
DB_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock

Seed Users in Database

Seeding is the process in which we insert fake records or information so that we can test the application while developing in real time.

You have to get inside the database/seeders/DatabaseSeeder.php file and add the given code into the file.

<?php

namespace Database\Seeders;
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        \App\Models\User::factory(20)->create();

        \App\Models\User::factory()->create([
            'name' => 'Demo',
            'email' => 'demot@example.com',
        ]);
    }
}

To run all of your outstanding migrations, run the following artisan command:

php artisan migrate

Now, the code is placed at the correct location. Next, you must run the command to add the dummy data into the database magically.

php artisan db:seed

Create New Controller

A controller is the backbone of the laravel. Here, in this file, you can write as much code to build any number of functionality.

You can quickly generate the controller using the composer command.

php artisan make:controller StudentController

We have to create specific functions that will add sweet alert; therefore, enter into the app/Http/Controllers/StudentController.php file and make sure to replace the current code with the following code.

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

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

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

Build View Template

Enter into the resources/views/ directory; here you have to create a new file.

Ensure that you name it home.blade.php and insert given code into the file.

<!DOCTYPE html>
<html>
<head>
    <title>Laravel Sweet Alert Message Example</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/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 Ajax Sweetalert 2 Notification Example</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('users.removeData',$user->id) }}">Delete</button>
                </td>  
            </tr>
        @endforeach
    </table>
          
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.7.27/dist/sweetalert2.all.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11.7.27/dist/sweetalert2.min.css" rel="stylesheet">
    <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>
</body>
</html>

Create New Routes

Next, we will be building two new routes one for requesting a controller for opening the view template on the browser and another for validating the input.

Make sure to add given code into the routes/web.php file.

<?php

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

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
*/

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

Run Development Server

We have reached to the last step of our guide; now we need to run the laravel app.

Run the command to evoke the server.

php artisan serve

Test your app by opening the app on the browser with given link.

http://127.0.0.1:8000/users

How to Show Notification using Sweet Alert in Laravel

Conclusion

If we don’t care about our users’ experience, they will certainly not care about us.

Hence, In this guide, we have learned how to use sweet alert in laravel and display important messages to site visitors.

The sweet alert is a BEAUTIFUL, RESPONSIVE, CUSTOMIZABLE, ACCESSIBLE (WAI-ARIA) library that has replaced JavaScript’s Popup Boxes.

Get Complete Documentation Here.

Digamber - Author positronX.io

Hi, I'm Digamber Singh, a New Delhi-based full-stack developer, tech author, and open-source contributor with 10+ years' experience in HTML, CSS, JavaScript, PHP, and WordPress.