DEV Community

Cover image for Global livewire notifications with SweetAlert
Pedro Henrique
Pedro Henrique

Posted on • Updated on

Global livewire notifications with SweetAlert

EDIT: I created a new idea for this, go to https://github.com/PH7-Jack/wireui to know

It is normal in all software after performing an action, showing a confirmation message or even a warning. With Livewire software development is simpler in some ways, but showing notifications can be a bit of a chore at first. With that, we can take advantage of what Livewire has in its ecosystem for our benefit.
Let's use Livewire events

Step 1

Add listeners

In this step, we will prepare the project to listen to livewire events
In your global layout file, place the following listener (in my case it's resources/views/components/layouts/base.blade.php):

<head>
...
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/7.33.1/sweetalert2.css" />
...
</head>

...
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@9"></script>
 <script>
        const SwalModal = (icon, title, html) => {
            Swal.fire({
                icon,
                title,
                html
            })
        }

        const SwalConfirm = (icon, title, html, confirmButtonText, method, params, callback) => {
            Swal.fire({
                icon,
                title,
                html,
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText,
                reverseButtons: true,
            }).then(result => {
                if (result.value) {
                    return livewire.emit(method, params)
                }

                if (callback) {
                    return livewire.emit(callback)
                }
            })
        }

        const SwalAlert = (icon, title, timeout = 7000) => {
            const Toast = Swal.mixin({
                toast: true,
                position: 'top-end',
                showConfirmButton: false,
                timer: timeout,
                onOpen: toast => {
                    toast.addEventListener('mouseenter', Swal.stopTimer)
                    toast.addEventListener('mouseleave', Swal.resumeTimer)
                }
            })

            Toast.fire({
                icon,
                title
            })
        }

        document.addEventListener('DOMContentLoaded', () => { 
            this.livewire.on('swal:modal', data => {
                SwalModal(data.icon, data.title, data.text)
            })

            this.livewire.on('swal:confirm', data => {
                SwalConfirm(data.icon, data.title, data.text, data.confirmText, data.method, data.params, data.callback)
            })

            this.livewire.on('swal:alert', data => {
                SwalAlert(data.icon, data.title, data.timeout)
            }) 
        })
    </script>
Enter fullscreen mode Exit fullscreen mode

These methods and listeners will show confirmation notifications or confirmation alerts globally in your project, being able to broadcast directly from Livewire

How to fire theses functions?

In every Livewire component you can send events using the code below

<?php

namespace App\Http\Livewire;

use Livewire\Component;

class MyComponent extends Component
{
    public function render()
    { 
        return view('livewire.shared.my-component');
    }

    public function showModal()
    { 
        $this->emit('swal:modal', [
            'type'  => 'success',
            'title' => 'Success!!',
            'text'  => "This is a success message",
        ]);
    }

    public function showAlert()
    { 
        $this->emit('swal:alert', [
            'type'    => 'success',
            'title'   => 'This is a success alert!!', 
            'timeout' => 10000
        ]);
    }

    public function showConfirmation()
    { 
        $this->emit("swal:confirm", [
            'type'        => 'warning',
            'title'       => 'Are you sure?',
            'text'        => "You won't be able to revert this!",
            'confirmText' => 'Yes, delete!',
            'method'      => 'appointments:delete',
            'params'      => [], // optional, send params to success confirmation
            'callback'    => '', // optional, fire event if no confirmed
        ]);
    }
}
Enter fullscreen mode Exit fullscreen mode

Latest comments (11)

Collapse
 
sterlaznikow profile image
PiMyLife

very poorly explained. could use a simple example

Collapse
 
bayu profile image
Diarsa

hello, what's mean the 'method' => 'appointments:delete', after confirm delete? is the livewire method? or route named?

Collapse
 
ph7jack profile image
Pedro Henrique

is a name of livewire listener

Collapse
 
bayu profile image
Diarsa

if my namespace is namespace App\Http\Livewire\Admin\Main; and the class is Org, and method I want to call is delete, then what should I fill in the 'method' ?

Thread Thread
 
ph7jack profile image
Pedro Henrique

you put the name of the listener, no matter where the class is, what is taken into account is the name of the listener.
An important point to think about is that there can be 2 components with the "delete" listener, so put a prefix in this case, ex: "user: delete" and "team: delete"

Thread Thread
 
bayu profile image
Diarsa

I try to protected $listeners = ['confirm' => 'syncFromDC']; but nothing happen after click Oke.

Thread Thread
 
bayu profile image
Diarsa
Thread Thread
 
8rux40 profile image
Bruno Tardin • Edited

Any solution? Same thing here... After confirm the dialog nothing happens.
This is some of my User class:

public function confirmDelete($id){
        $this->emit("swal:confirm", [
            'type'        => 'warning',
            'title'       => 'Tem certeza?',
            'text'        => "Você não poderá reverter isso!",
            'confirmText' => 'Sim, desativar!',
            'method'      => 'usuario:delete',
            'params'      => $id, // optional, send params to success confirmation
            'callback'    => '', // optional, fire event if no confirmed
        ]);
    }

public function delete($id) {
        if ($id){
            User::find($id)->delete();
            $this->emit('swal:alert', [
                'type'  => 'success',
                'title'  => "Usuário desativado com sucesso!",
                'timeout' => 3000,
            ]);
        }
    }
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
8rux40 profile image
Bruno Tardin

Works for me now that I have declared the $listeners in my Usuario class:

protected $listeners = ['usuario:delete' => 'delete'];
...
public function confirmDelete($id){
        ...
    }

public function delete($id) {
        ...
    }
Enter fullscreen mode Exit fullscreen mode
Collapse
 
saaberdev profile image
Mahfuzur Rahman Saber

Hey brother, can you please tell me how these parts are working ??

'method' => 'appointments:delete',
'params' => [], // optional, send params to success confirmation
'callback' => '', // optional, fire event if no confirmed

Collapse
 
ph7jack profile image
Pedro Henrique

Hello
in the key method, inform the livewire listener that will receive the event
the parameter key is to pass data to this event, like an id, name ..
the callback key is used when confirmation is denied, eg ask to delete, if the answer is no, call event X