Import SweetAlert2 into Laravel with NPM

David Carr

Javascript Laravel Framework Tutorials

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>

 

Read articles directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Copyright © 2006 - 2024 DC Blog - All rights reserved.