Livewire confirm Sweet Alert

David Carr

Laravel Livewire

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

Fathom Analytics $10 discount on your first invoice using this link

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

Sponsor

Fathom Analytics $10 discount on your first invoice using this link

Subscribe to my newsletter

Subscribe and get my books and product announcements.

© 2006 - 2024 DC Blog. All code MIT license. All rights reserved.