Hi, my name is David Carr and I'm a PHP Developer.


Blog Archives Categories Authors About Me Open Source Books Contact Me

Sponsor Me

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

My Latest Book

Laravel: The Modular way

Learn how to build modular applications with Laravel Find out more

Laravel Livewire

David Carr

Livewire confirm Sweet Alert

Using Sweet alerts with Livewire is possible by triggering events from Livewire / AlpineJs and having javascript listen for the event and act when it's triggered.

On a link or button using wire:click we can trigger sending an event using $emit it takes 2 params 

1) the event name
2) the value to pass

<button wire:click="$emit('triggerDelete',{{ $contact->id }})" type="button">Delete</button>

Then in a view when the event is triggered a closure will file. From there a normal Sweet Alert is executed. When a confirmation runs the if result.value runs then triggers a method on the Livewire controller called delete and pass in the value.

@push('scripts')
<script type="text/javascript">
    document.addEventListener('DOMContentLoaded', function () {

        @this.on('triggerDelete', id => {
            Swal.fire({
                title: 'Are You Sure?',
                html: "You won't be able to revert this!",
                icon: 'warning',
                showCancelButton: true,
            }).then((result) => {
                if (result.value) {
                    @this.call('delete',id)
                }
            });
        });
    })
</script>
@endpush

This approach is dead simple and allows Livewire and Sweet Alerts to work together.

You could trigger the event from a Livewire controller if you prefer.

Thanks to BezhanSalleh for posting the solution on Laracasts

Copyright © 2009 - 2022 David Carr. All code MIT license. All rights reserved.