How to Install SweetAlert2 in Laravel 13 with Vite: Alerts and Delete Confirmations

2026-11-13来源 dev.toEnglish

To use SweetAlert2 in Laravel 13, install it with npm (npm install sweetalert2), import it in resources/js/app.js, expose it on window and rebuild with Vite. Then you can show alerts from JavaScript or from session flash data, and ask for confirmation before a delete. This tutorial covers installation, a flash-message alert and a safe delete confirmation.

Targets: Laravel 13 (PHP 8.3 to 8.5), Vite and the sweetalert2 npm package. The example uses Blade templates.

Step 1: Install the package

npm install sweetalert2 

Step 2: Import it in app.js

Open resources/js/app.js and add:

import Swal from 'sweetalert2'; window.Swal = Swal; 

Putting Swal on window lets inline scripts in Blade views use it. The package ships its own styles inside the JavaScript, so you normally do not need to import a CSS file.

Step 3: Load the assets in your layout

Make sure your layout includes the Vite assets in the head:

@vite(['resources/css/app.css', 'resources/js/app.js']) 

During development run npm run dev. For production, run npm run build. If you skip this, the page uses the old build and Swal is undefined.

Step 4: Show a simple alert

Swal.fire({ title: 'Saved!', text: 'Your changes were saved.', icon: 'success', confirmButtonText: 'OK', }); 

The icon option accepts success, error, warning, info and question.

How do I show Laravel flash messages with SweetAlert2?

Add this block at the end of your layout, below the Vite assets. It uses the @session directive and prints the message with JSON encoding, which protects against quote injection:

@session('success') <script> Swal.fire({ icon: 'success', title: @js($value), timer: 2500, showConfirmButton: false, }); </script> @endsession @session('error') <script> Swal.fire({ icon: 'error', title: 'Something went wrong', text: @js($value), }); </script> @endsession 

In your controller, flash the message as usual: return back()->with('success', 'Post saved.');. The @js directive converts the PHP value into a safe JavaScript literal.

How do I confirm before deleting a record?

Use a normal form for the delete so it works with CSRF and method spoofing, and let JavaScript intercept the submit:

<form method="POST" action="{{ route('posts.destroy', $post) }}" class="js-delete-form"> @csrf @method('DELETE') <button type="submit">Delete</button> </form> 
document.addEventListener('submit', (event) => { const form = event.target.closest('.js-delete-form'); if (!form) return; event.preventDefault(); Swal.fire({ title: 'Delete this item?', text: 'This action cannot be undone.', icon: 'warning', showCancelButton: true, confirmButtonText: 'Yes, delete it', cancelButtonText: 'Cancel', }).then((result) => { if (result.isConfirmed) { form.submit(); } }); }); 

Put this script in resources/js/app.js after the window.Swal line. Event delegation on document means it also works for forms added later, for example in paginated tables. If the user closes the dialog, the form is never submitted. Do not rely on the dialog for security: the server must still check authorization in the controller or policy.

How do I change the colors and style?

Pass confirmButtonColor and cancelButtonColor, or use the customClass option to add your own CSS classes (for example Tailwind or Bootstrap classes). To apply the same defaults everywhere, create a configured instance:

window.Toast = Swal.mixin({ toast: true, position: 'top-end', showConfirmButton: false, timer: 3000, timerProgressBar: true, }); 

Then call Toast.fire({ icon: 'success', title: 'Copied' }) for small notifications in the corner.

How do I check that it works?

  1. Run npm run dev and open a page. In the browser console, type Swal.fire('Hello'). A dialog should appear.
  2. Save a record that flashes success and confirm the alert appears and closes after a moment.
  3. Click Delete, press Cancel and confirm nothing is deleted. Click again and confirm the delete works.

Common mistakes

  • Swal is not defined: you forgot window.Swal = Swal or the Vite build is stale. Restart npm run dev or rebuild.
  • Printing messages with raw quotes: use @js() so a quote in the message cannot break the script.
  • Using a link for delete: deletes should be POST with @method('DELETE'), not a GET link.
  • Loading the script twice: a second copy from a CDN and one from npm can cause duplicate dialogs.
  • Trusting the client: always authorize the delete on the server.

FAQ

Can I use a CDN instead of npm?

Yes, but with Vite the npm approach gives you one bundled file and a pinned version in package.json.

Does it work with Livewire?

Yes. Dispatch a browser event from the component and listen to it in JavaScript, or call Swal.fire() in a script that reacts to Livewire events.

Is SweetAlert2 free?

The package is open source under the MIT license. Check the project's page for any sponsorship notes.

References

Originally published on yasiramin.dev.

原文:https://www.a8q9.cn/en/article/how-to-install-sweetalert2-in-laravel-13-with-vite-alerts-and-delete-confirmatio-172074.html

相关文章