DEV Community

Cover image for Adding SweetAlert2 to Laravel (The Laravel-Mix Way)
Dendi Handian
Dendi Handian

Posted on • Updated on

Adding SweetAlert2 to Laravel (The Laravel-Mix Way)

There is a case in any app when you are about to make changes that crucial or dangerous, we tend to confirm the user. There are many ways to display a confirmation dialog to the user, such as using a modal pop-up or simply using a plain javascript confirm alert like this:

<a href="https://dev.to/dendihandian" onclick="return confirm('Do you want to go?')">Link</a>
Enter fullscreen mode Exit fullscreen mode

That simple way is too plain or looks ugly if everything else on your app is so fancy. And that's how SweetAlert comes in handy for this, easy to implement and yet customizable to make it prettier. In Laravel, we could implement it using Laravel-Mix.

Prerequisites to code along

Prepare your own existing or new ready-to-be-developed laravel app and make sure to have NodeJS & NPM installed on your machine.

Installing SweetAlert2

npm install sweetalert2 --save-dev
Enter fullscreen mode Exit fullscreen mode

Confirm a delete action using SweetAlert

Let's say we have this button and form (this example may not be accurate, so fix it for your own case) for a product with id 39. If we click the DELETE button, a confirmation dialog should be showing up.

<a href="#" onclick="deleteConfirm('delele-product-form-39')">Delete</a>
<form id="delete-product-form-39" action="http://myapp.test/product/39/delete" method="POST"></form>
Enter fullscreen mode Exit fullscreen mode

and then we have to make the deleteConfirm() function to show the confirmation dialog. So, in the default laravel resource/js/app.js file, let's add this code:


...

import Swal from 'sweetalert2';

window.deleteConfirm = function(formId)
{
    Swal.fire({
        icon: 'warning',
        text: 'Do you want to delete this?',
        showCancelButton: true,
        confirmButtonText: 'Delete',
        confirmButtonColor: '#e3342f',
    }).then((result) => {
        if (result.isConfirmed) {
            document.getElementById(formId).submit();
        }
    });
}
Enter fullscreen mode Exit fullscreen mode

Don't forget to re-build using:

npm run development
Enter fullscreen mode Exit fullscreen mode

or

npm run production
Enter fullscreen mode Exit fullscreen mode

Alt Text

And the button and confirmation should be work. You may want to use sweetalert for flash messages too, so have the experiment on it.


version used:

laravel-mix 5.0.7
sweetalert2 10.10.1

nodejs v14.15.1
npm 6.14.8
Enter fullscreen mode Exit fullscreen mode

Top comments (0)