DEV Community

loading...
Cover image for Use SweetAlert2 with Laravel Livewire

Use SweetAlert2 with Laravel Livewire

M H Hasib
I'm a web/software developer from Bangladesh. I write about PHP, Laravel Framework, MySQL & GraphQL and love to share my knowledge with others.
・2 min read

Recently I've been doing a lot of Laravel Livewire stuff and truth to be told, I'm falling in love with it.

One of the common things to do in a web application is showing toast notifications. In this article, I'll be sharing a strategy I've been following for a while now.

Let's jump to implementing Sweet Alert 2 with Laravel Livewire.

Step 1:

First of all, we need to install Sweet Alert 2. You can install it through npm.

npm install sweetalert2
Enter fullscreen mode Exit fullscreen mode

Or you can use this through CDN. In this article, I am going to use with CDN.

<script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>
Enter fullscreen mode Exit fullscreen mode

Put this CDN in your Main Layout.

Step 2:

Now, If you use this in Laravet Livewire, you should have a Livewire Component and Class. So in that class, after doing an action you need to dispatch a browser event. Now put this code into your action.

$this->dispatchBrowserEvent('swal', [
    'title' => 'Item has been removed.',
    'icon'=>'success',
    'iconColor'=>'blue',
]);
Enter fullscreen mode Exit fullscreen mode

Step 3:

Now you need to listen to this event so that it can fire an action to show the Sweet Alert Message. Now put this code to listen to the event which is fired from the Component Class.

<script>
    window.addEventListener('swal',function(e) {
        Swal.fire({
            title:  e.detail.title,
            icon: e.detail.icon,
            iconColor: e.detail.iconColor,
            timer: 3000,
            toast: true,
            position: 'top-right',
            toast:  true,
            showConfirmButton:  false,
        });
    });
</script>
Enter fullscreen mode Exit fullscreen mode

Here we go... We have done our job.

Here I am sharing a GitHub Repository for making you better understand how you can use it.

Here I used this code as partials/_swal.blade.php.

<script>
    window.addEventListener('swal',function(e) {
        Swal.fire({
            title:  e.detail.title,
            icon: e.detail.icon,
            iconColor: e.detail.iconColor,
            timer: 3000,
            toast: true,
            position: 'top-right',
            toast:  true,
            showConfirmButton:  false,
        });
    });
</script>
Enter fullscreen mode Exit fullscreen mode

Then I imported it in layouts/app.blade.php. You can easily understand it after seeing this repository.

Suggested Reads

Discussion (2)

Collapse
shumonbalok profile image
shumonbalok

Thanks for sharing

Collapse
mahmudulhsn profile image
M H Hasib Author

Welcome bro...