Search code examples
laravel-livewire

Livewire flash message appears only once when action if performed


hello everyone i just wanna know how to make a flash message appears everytime when an action is performed. I have an categories table in my blade and at the end of every row there is a delete button when i press it the action is performed successfully and my flash message appears as a Popup (SweetAlert2) but when i delete another row the delete function runs successfully but the popup doesn't appear again.

In my blade

@if(session()->has('process-error')) 
<script>
    Swal.fire(
        'Error',
        '{{ session('process-error') }}',
        'error'
    )
</script>
@endif
@if(session()->has('process-success'))
    <script>
        Swal.fire(
            'Success',
            '{{ session('process-success') }}',
            'success'
        )
    </script>
@endif       

in my component

    public function delete($id)
    {
        $categoriesService = CategoriesService::deleteCategory($id);

        if(!$categoriesService)
        {
            // RETURN AN ERROR MESSAGE
            session()->flash('process-error' , 'Failed to delete the category');
            return;
        }

        // RETURN A SUCCESS MESSAGE
        session()->flash('process-success' , 'Category deleted successfully!');
    }

Solution

  • if you have installed Swall you don't need to show it through session()->flash(). You can dispatch a js event and capture it like

    if(!$categoriesService)
    {
       // RETURN AN ERROR MESSAGE
       $this->dispatchBrowserEvent('process-swall',['type' => 'error']);
       return;
    }
    
    // RETURN A SUCCESS MESSAGE
       $this->dispatchBrowserEvent('process-swall' ,['type' => 'success']);
    }
    
     //in script section
    
    <script>
       window.addEventListener('process-swall', event => {
           let type = event.detail.type;
           let message = type === 'success' ? 'Category deleted successfully!' : 'Failed to delete the category';
           let camelCaseType = type === 'success' ? 'Success' : 'Error';
           Swal.fire(
                camelCaseType,
                message,
                type
            )
       })
    </script>