Laravel 11 - How to Integrate SweetAlert2

Touseef Afridi
25 Dec 24

Laravel 11 - How to Integrate SweetAlert2

In this tutorial, we will discuss how to integrate SweetAlert2 in Laravel 11 and explore its benefits, such as creating stylish, interactive alerts to enhance user engagement and improve the overall user experience.


If you're a video person, feel free to skip the post and check out the video instead!


Quick Overview

This guide walks you through integrating SweetAlert2 with Laravel 11 to enhance user notifications. It begins by creating a fresh Laravel project and setting up the necessary environment using Composer or the Laravel installer. After navigating to the project directory, a new route (/sweet) is defined in routes/web.php to load a dedicated Blade view (sweet.blade.php). This view is designed with Tailwind CSS for styling and includes jQuery and SweetAlert2 via CDN. It features two interactive buttons—one triggering a success alert and another displaying an error alert—both handled using jQuery click events. The alerts are created with Swal.fire(), offering a visually appealing alternative to default browser pop-ups. Finally, the Laravel development server is started, allowing you to test the implementation by accessing 127.0.0.1:8000/sweet, where you can see SweetAlert2 in action. This setup improves user experience by replacing basic alerts with modern, interactive modals.

Step # 1 : Create fresh Laravel project or use existing Laravel project.

If you have Laravel Globally installed, you can use below command to create a fresh project named sweetAlert2.
laravel new sweetAlert2
Or use
Alternatively, if Laravel is not installed globally, use the Composer command.
composer create-project laravel/laravel --prefer-dist sweetAlert2
After running either command, you'll be prompted with a series of setup options.
  1. Would you like to install the starter kit? — Select none.
  2. Select the testing framework. — Choose Pest.
  3. Select the database for your application. — Choose mysql.
  4. Run the default database migration? — Select yes.

Once these steps are completed, Laravel will generate a new project directory named sweetAlert2, set up the necessary files and dependencies, and configure the database with default migrations. Your Laravel project will be ready for further development, allowing you to easily implement features and customize it according to your requirements.

Step # 2 : Access the project.

Open a terminal (e.g., Git Bash) and navigate to your Laravel project's root folder.
cd c:xampp/htdocs/sweetAlert2
This will set your working directory to the Laravel project, allowing you to execute further commands like running the development server, installing packages, or modifying project files.

Step # 3 : Create a route.

Define a route in the routes/web.php file using the following code.
Route::get('/sweet', function(){
 return view('sweet');
});
This route maps the /sweet URL to a view named sweet. When a user visits this URL in a browser, Laravel will load and display the sweet.blade.php view file from the resources/views directory.

Step # 4 : Create a view.

Create a new Blade file called sweet.blade.php inside the resources/views/ directory. This file will contain the HTML, CSS, and JavaScript code to implement the SweetAlert2 alerts.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Code Shotcut - SweetAlert</title>
    <!-- Tailwind CSS CDN -->
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        success: '#10B981',
                        error: '#EF4444',
                    },
                },
            },
        };
    </script>
</head>
<body class="bg-gray-900 text-white">
<div class="container mx-auto text-center py-16">
    <h1 class="text-4xl font-extrabold mb-8">SweetAlert2 in Laravel 11</h1>
    <p class="text-lg mb-4">SweetAlert2 is a powerful JavaScript library for creating interactive and visually appealing alerts in web applications.</p>
    <p class="text-lg mb-8">We use it to replace default browser alerts with custom, responsive modals for better user experience and flexibility.</p>
    <div class="flex justify-center space-x-4">
        <button class="flex items-center px-6 py-3 bg-success hover:bg-green-700 text-white font-semibold rounded shadow-lg transition duration-200" id="success-alert">
            <svg class="w-5 h-5 mr-2" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                <path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7" />
            </svg>
            Success Alert
        </button>
        <button class="flex items-center px-6 py-3 bg-error hover:bg-red-700 text-white font-semibold rounded shadow-lg transition duration-200" id="error-alert">
            <svg class="w-5 h-5 mr-2" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" />
            </svg>
            Error Alert
        </button>
    </div>
</div>
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<!-- SweetAlert2 via CDN -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<!-- SweetAlert2 Script -->
<script>
    // Success Alert
    $('#success-alert').on('click', function() {
        Swal.fire({
            title: 'Success!',
            text: 'This task has been performed successfully and everything is working as expected.',
            icon: 'success',
            confirmButtonText: 'Cool'
        });
    });
    // Error Alert
    $('#error-alert').on('click', function() {
        Swal.fire({
            title: 'Error!',
            text: 'An error occurred while processing your request. Please try again or contact support if the issue persists.',
            icon: 'error',
            confirmButtonText: 'Try Again'
        });
    });
</script>
</body>
</html>
This Blade view sweet.blade.php serves as the front-end interface for implementing SweetAlert2 in Laravel 11. It includes Tailwind CSS via CDN for styling and imports jQuery and SweetAlert2 to enable alert functionality. The view contains two buttons—one for triggering a success alert and another for an error alert. Using jQuery, button clicks are handled to trigger SweetAlert2 alerts via Swal.fire(), which displays a modal with a title, message, and alert type (success or error). Clicking the Success Alert button shows a green confirmation message, while the Error Alert button displays a red error message. This setup enhances user experience by replacing standard browser alerts with stylish, interactive modals.

Step # 5 : It's time to test.

Start the Laravel development server by running the command.
php artisan serve
Once the server is running, open your browser and navigate to.
127.0.0.1:8000/sweet


This will load the sweet.blade.php view, where you can test the success and error alerts triggered by SweetAlert2. Clicking the Success Alert button will display a green confirmation message, while clicking the Error Alert button will show a red error message. These alerts provide a better user experience by replacing default browser alerts with visually appealing modals.

Conclusion

By following this process, you can seamlessly integrate SweetAlert2 into your Laravel 11 application, offering a more dynamic and engaging user experience with custom, interactive alerts. With Tailwind CSS for styling, you can ensure a modern, responsive design, while jQuery handles the events that trigger the alerts. This setup allows you to easily implement success and error modals that provide visually appealing feedback to users. Replacing the standard browser alerts with SweetAlert2 gives your application a polished feel, improving its overall user interface. Moreover, SweetAlert2's flexibility lets you tailor alert types, messages, and animations to fit various scenarios, ensuring a highly customizable solution. Whether you're handling form submissions, notifications, or system errors, SweetAlert2 enhances the interactivity of your application. This integration also paves the way for future enhancements, such as custom alert themes and multi-step modals, giving you even more control over the user experience.
For more details, please refer to the SweetAlert2 documentation.
Share this with friends!


"Give this post some love and slap that 💖 button as if it owes you money! 💸😄"
0

0 Comments

To engage in commentary, kindly proceed by logging in or registering