Laravel 10 - SweetAlert2

Touseef Afridi
04 Sep 24

Laravel 10 - SweetAlert2

In this video, we’ll see how to implement SweetAlert in Laravel 10, offering sleek pop-up notifications for success, errors, and more to improve user experience.


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


Quick Overview

In this guide, we walk you through integrating SweetAlert2 into a Laravel 10 application to display clean and responsive alert messages. You’ll begin by setting up a new or existing Laravel project, then install frontend dependencies and launch the Vite development server. Next, you’ll define a test route and create a Blade view that includes Bootstrap and SweetAlert2 via CDN. Inside the view, you'll add buttons that trigger success and error alerts using jQuery and the Swal.fire() method. Finally, you’ll run your Laravel app and test the alerts in your browser. By the end of this guide, you’ll have a simple yet powerful alert system ready for use in forms, actions, or notifications, enhancing your app’s user experience with minimal effort. It’s an easy way to add a modern touch to your interface while keeping your code clean and maintainable.

Step # 1 : Create a Laravel 10 Project (Fresh or Existing)

Let’s kick things off by setting up your Laravel 10 environment. If you already have a Laravel project running, feel free to skip ahead, but if you’re starting from scratch, here’s how to set it up. If Laravel is installed globally on your system, you can quickly spin up a new project by running the following command.
laravel new sweetalert
Alternatively, if you’re using Composer (which works great too), you can run.
composer create-project laravel/laravel --prefer-dist sweetalert
This will create a fresh Laravel 10 project named sweetalert. It gives us a clean foundation to work with and makes it easier to test out SweetAlert without any clutter. Whether you're experimenting with frontend tools or building out a new feature, starting with a fresh environment helps keep things organized and bug-free.

Step # 2 : Navigate to the Project and Set Up Frontend Assets.

Once the project is ready, open your terminal (such as Git Bash or your preferred shell) and move into your Laravel project folder. For example.
cd c:xampp/htdocs/sweetalert
Now, install the frontend dependencies and start the Vite development server.
npm install && npm run dev
Keep this terminal running to serve your frontend assets. Then, open a new terminal window or tab, return to the same project directory, and you’ll be ready to run additional Laravel commands as needed.

Step # 3 : Add a Route for Testing.

Now that our Laravel project is set up, let’s create a simple route to display the SweetAlert test page. Open the web.php file located in the routes/ directory. This is where we define the URLs (routes) that our application responds to. Add the following code snippet.
Route::get('/sweet', function () {
    return view('sweet');
});
This route listens for GET requests made to /sweet and returns the sweet Blade view we’ll create shortly. Once added, you can visit http://localhost:8000/sweet in your browser, and Laravel will load the corresponding page. This gives us a convenient spot to test SweetAlert in action without setting up a full controller or backend logic. It’s a great way to keep things simple and focused while experimenting.

Step # 4 : Create a view.

Now that we have our test route in place, let’s build the actual view that will render the SweetAlert popups. Head over to the resources/views directory and create a new Blade file named sweet.blade.php. This will be the template loaded when we visit our /sweet route in the browser. Inside this file, paste the following code.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test SweetAlert</title>
    <!-- Bootstrap 4 CDN -->
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container text-center mt-5">
    <h1 class="mb-4">SweetAlert2 in Laravel 10</h1>
    <button class="btn btn-success" id="success-alert">Success Alert</button>
    <button class="btn btn-danger" id="error-alert">Error Alert</button>
</div>
<!-- jQuery and Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.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 is a success alert.',
            icon: 'success',
            confirmButtonText: 'Cool'
        });
    });
    // Error Alert
    $('#error-alert').on('click', function() {
        Swal.fire({
            title: 'Error!',
            text: 'Something went wrong.',
            icon: 'error',
            confirmButtonText: 'Try Again'
        });
    });
</script>
</body>
</html>
This simple Blade view pulls in Bootstrap 4 for clean styling and SweetAlert2 via a CDN to handle the alerts. Inside the view, we’ve added two interactive buttons, one for success and another for error handling, each wired up using jQuery. When clicked, they trigger a modal popup using Swal.fire(), which displays a styled message box with a title, description, and matching icon. This setup not only helps you test SweetAlert functionality in a clean and isolated environment but also serves as a solid foundation for real-world use cases, such as displaying alerts after form submissions, showing error messages, or confirming actions. With just a few lines of code, you’ve now introduced a sleek, user-friendly alert system into your Laravel application that can be reused and customized throughout your project.

Step # 5 : Run and Test the App.

Now it’s time to see everything in action. Start the Laravel development server by running the following command in your project directory.
php artisan serve
Once it’s up, open your browser and head to: http://127.0.0.1:8000/sweet. You’ll be greeted with a clean interface featuring two buttons. Go ahead, click them! Each button should trigger a beautifully styled SweetAlert popup, one showing a success message, the other an error alert. This quick test confirms that SweetAlert2 is working correctly within your Laravel app and that everything you’ve set up so far is functioning just as expected. It’s a small but satisfying win that sets the stage for more advanced integrations.


Conclusion

By following this step-by-step guide, you’ve successfully integrated SweetAlert2 into your Laravel 10 application. From setting up the environment and frontend assets to creating a test route and crafting a responsive view, you now have a working example of stylish, interactive alerts using SweetAlert2. These alerts enhance the user experience by providing visually engaging feedback, ideal for success confirmations, error messages, or custom notifications. The setup is lightweight, beginner-friendly, and can easily be extended across different parts of your application. You can now confidently use SweetAlert2 to replace default browser alerts with more elegant and user-friendly alternatives in your Laravel projects.

For more examples, animations, or advanced features like modals, input prompts, and AJAX support, feel free to explore the official documentation at sweetalert2.github.io.
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