Notification alerts serve as critical communication channels between machines and humans, emphasizing the message’s significance. This tutorial on sweet alert notifications guides you through integrating the sweet alert library to effectively display alerts in your Laravel application.
Laravel 11 Notifications using Sweet Alert Example
Sweet Alert is renowned for its compact yet powerful features that enable detailed tracking of user interactions with alerts. Its flexibility in customization is a standout feature.
Step 1: Create Laravel Project
To demonstrate how to use alert notification messages, we need to set up a new Laravel application.
Ensure Composer is installed on your development environment, and then execute the following command:
composer create-project laravel/laravel --prefer-dist laravel-app
Navigate into the newly created project directory:
cd laravel-app
Step 2: Configure Database Connection
Since our application will store user data in a database, we must configure Laravel to connect to the SQL database by updating the .env file.
Here’s an example of the database configuration:
DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=laravel_db
DB_USERNAME=root
DB_PASSWORD=
Step 3: Insert Dummy data in Database using Seeder
Seeding involves inserting dummy data or records into the database to facilitate testing during development.
To seed the database, modify the database/seeders/DatabaseSeeder.php file with the following code:
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use App\Models\User;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* @return void
*/
public function run()
{
User::factory(20)->create();
User::factory()->create([
'name' => 'Demo',
'email' => 'demot@example.com',
]);
}
}
Run migrations to apply any pending database changes:
php artisan migrate
Once migrations are complete, populate the database with the seeded data:
php artisan db:seed
Step 4: Create a New Controller
Controllers are essential for building application logic in Laravel. Generate a new controller using Artisan:
php artisan make:controller StudentController
Modify the app/Http/Controllers/StudentController.php file with the following code to implement functionality that includes Sweet Alert:
<?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();
}
}
Step 5: Create a View Template
Navigate to the resources/views/ directory and create a new Blade template file named home.blade.php. Insert the following 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>
Step 6: Define New Routes
To access the views and handle form submissions, define new routes in 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');
Step 7: Launch the Development Server
To run the Laravel application, execute the following command:
php artisan serve
Test your application by navigating to the following link in your browser:
http://127.0.0.1:8000/users
In this guide, we’ve explored how to integrate Sweet Alert into Laravel to display meaningful notifications to site visitors. Sweet Alert is a library that provides beautiful, responsive, customizable, and accessible (WAI-ARIA) alerts, replacing traditional JavaScript popup boxes.