Currently seeking new career opportunities in web development, particularly with Laravel, Hire Me

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

Laravel Modules Your Logo Your Logo Your Logo

Become a sponsor

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

Sponsor

My Latest Book

Modular Laravel Book - Laravel: The Modular way

Learn how to build modular applications with Laravel Find out more

Subscribe to my newsletter

Subscribe and get my books and product announcements.

Learn Laravel with Laracasts

Faster Laravel Hosting

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