Import SweetAlert2 into Laravel with NPM

David Carr

Tutorials Javascript Laravel Framework

SweetAlert2 is a great package for user-friendly alerts, normally I install by adding in script tags and then use the package as normal. This post will explain how to instead install with NPM in Laravel.

First, open your Laravel project in the terminal and add

npm install sweetalert2

This will install the package into package.json that looks like:

"dependencies": {
    "sweetalert2": "^10.15.5"
}

Next, we need to import SweetAlert2 into resources/js/app.js 

Import to make the package available to the current file

import swal from 'sweetalert2';

If you want to use SweetAlert2 globally you can add it to a window object:

window.Swal = swal;

This can then be used directly in app.js or in any blade file.

Now we need to compile the changes into app.js by running:

npm run dev

Using SweetAlert2 in a Blade file

To use in a blade file lets you need to ensure the content is loaded before attempting to use SweetAlert2 otherwise you will get an error. To do this we can add an event listener called DOMContentLoaded which will run only when the content is ready.

<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function () {
   //content goes here
});
</script>

Here's an example of a confirmation alert:

<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function () {
   Swal.fire({
      title: 'Are you sure?',
      text: "You won't be able to revert this!",
      icon: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#3085d6',
      cancelButtonColor: '#d33',
      confirmButtonText: 'Yes, delete it!'
    }).then((result) => {
      if (result.isConfirmed) {
        Swal.fire(
          'Deleted!',
          'Your file has been deleted.',
          'success'
        )
      }
    })
});
</script>

 

Fathom Analytics $10 discount on your first invoice using this link

David Carr - Laravel Developer

Hi, I’m David Carr

A Senior Developer at Vivedia
I love to use the TALL stack (Tailwind CSS, Alpine.js, Laravel, and Laravel Livewire)

I enjoy writing tutorials and working on Open Source packages.

I also write books. I'm writing a new book Laravel Testing Cookbook, This book focuses on testing coving both PestPHP and PHPUnit.

Sponsor me on GitHub

Subscribe to my newsletter

Subscribe and get my books and product announcements.

Laravel Testing Cookbook

Help support the blog so that I can continue creating new content!

Fathom Analytics $10 discount on your first invoice using this link

Subscribe to my newsletter

Subscribe and get my books and product announcements.

© 2006 - 2023 DC Blog. All code MIT license. All rights reserved.