Laravel-9 Tutorial – How to Show Notification using Sweet Alert in Laravel 9

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 9 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 9

  • 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.


namespace DatabaseSeeders;
use IlluminateDatabaseSeeder;
class DatabaseSeeder extends Seeder
{
    
    public function run()
    {
        AppModelsUser::factory(20)->create();
        AppModelsUser::factory()->create([
            'name' => 'Demo',
            'email' => 'demot@example.com',
        ]);
    }
}

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.


namespace AppHttpControllers;
use AppModelsUser;
use DB;
use IlluminateHttpRequest;
use IlluminateSupportFacadesHash;
class StudentController extends Controller
{
    
    public function usersList()
    {
        $students = User::all();
        return view('home', compact('students'));
    }
    public function removeUser($id)
    {
        $delete = User::where('id', $id)->delete();
        if ($delete == $id) {
            $success = true;
            $message = "Student successfully removed!";
        } else {
            $success = true;
            $message = "Student does not exist!";
        }
        
        return response()->json([
            'success' => $success,
            'message' => $message,
        ]);
    }
}

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 lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    
    <title>Laravel</title>
    
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" type="text/css" href="{{ asset('css/style.css') }}">
</head>
<body>
    <div class="container mt-5">
       <h2 class="mb-4">Laravel Alpha Validation Rule Examle</h2>
        @if(Session::has('success'))
            <div class="alert alert-success text-center">
                {{Session::get('success')}}
            </div>
        @endif    
        <form  method="post" action="{{ route('alpha-validate.form') }}" novalidate>
            @csrf
            <div class="form-group mb-2">
                <label>Name</label>
                <input type="text" class="form-control @error('name') is-invalid @enderror" name="name" id="name">
                @error('name')
                    <span class="invalid-feedback" role="alert">
                        <strong>{{ $message }}</strong>
                    </span>
                @enderror
            </div>
            <div class="d-grid mt-3">
              <input type="submit" name="send" value="Submit" class="btn btn-danger btn-block">
            </div>
        </form>
    </div>
</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.


use IlluminateSupportFacadesRoute;
use AppHttpControllersStudentController;

Route::get('/view-students', [StudentController::class, 'usersList']);
Route::post('/delete-student/{id}', [StudentController::class, 'removeUser']);

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/view-students

How to Show Notification using Sweet Alert in Laravel 9

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.

Leave a Reply

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