How to use SweetAlert2 with Livewire

Image for post
Image for post

I got too many requests for adding confirmation alerts feature to realrashid/sweet-alert package this realrashid/sweet-alert/issues/57 is one of the earliest request for adding confirmation alerts feature but unfortunately i haven’t added this feature yet because i haven’t found the best way to achieve this.

So Today I found an easy way to do this without adding the support for this feature in realrashid/sweet-alert package with the help of Livewire 🎉

So without any further due Let’s Begin 🔥

First Install the realrashid/sweet-alert package in your project if not installed yet 😢

composer require realrashid/sweet-alert

Then configure the package.

Include 'sweetalert::alert' view in master layout


and run the below command to publish the package assets.

php artisan sweetalert:publish

Yahoooooooo You Have Successfully Installed realrashid/sweet-alert 😉

For more info checkout the documentation.
sweet-alert/documentation 📘

Note: You have to enable SWEET_ALERT_ALWAYS_LOAD_JS in your .env file!


Congratulations now you can use the realrashid/sweet-alert package with Livewire 🎉 🎉

Now let’s install the Livewire then we go further 😎 .

composer require livewire/livewire

Include the JavaScript (on every page that will be using Livewire).

In our case this is our master layout there we included @include('sweetalert::alert')


Now let’s create a Livewire ConfirmAlert component.

php artisan make:livewire ConfirmAlert

Running this above command will generate the following two files:

// app/Http/Livewire/ConfirmAlert.php
// resources/views/livewire/confirm-alert.blade.php

Let’s first start with app/Http/Livewire/ConfirmAlert.php


Now Let’s edit the component view!

<!-- resources/views/livewire/confirm-alert.blade.php -->

You did it 🎉

Now just load the button within your blade.
In my case it is resources/views/contacts/index.blade.php.

<table class="table table-striped">
<td colspan=2>Actions</td>
@foreach($contacts as $contact)
<a href="...">Edit</a>
@livewire('confirm-delete', ['contactId' => $contact->id])

That’s it.

Thank you! 👍

Creator 0f 9Webb a Full Stack Developer, an Artisan lover. I live in a small town somewhere in the world.I am passionate about Web and Mobile apps development.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store