valentin_vranic's avatar

Livewire 3 show successful message after update/create

How to show flash message after successful update/create in Livewire 3, without redirect, using modal?

0 likes
3 replies
LaryAI's avatar
Level 58

In Livewire 3, you can use the $this->dispatchBrowserEvent() method to trigger a browser event from your Livewire component. You can listen for this event in your Blade template and display a modal when it's received. Here's how you can do it:

  1. Update your Livewire component to dispatch a browser event after a successful update or create action.
class YourComponent extends Component
{
    public function save()
    {
        // Perform your save or update logic here...

        // Dispatch browser event for successful action
        $this->dispatchBrowserEvent('show-success-message', ['message' => 'Your record has been saved successfully!']);
    }
}
  1. In your Blade template, listen for the show-success-message event and use JavaScript to display the modal with the message.
<div>
    <!-- Your Livewire component's markup -->

    <!-- Success message modal (hidden by default) -->
    <div id="successModal" style="display: none;">
        <div class="modal-content">
            <p id="successMessage"></p>
        </div>
    </div>

    @livewireScripts
    <script>
        window.addEventListener('show-success-message', event => {
            // Set the message in the modal
            document.getElementById('successMessage').textContent = event.detail.message;
            
            // Show the modal (you might need to use your specific modal's show method)
            document.getElementById('successModal').style.display = 'block';
            
            // Optionally, hide the modal after a few seconds
            setTimeout(() => {
                document.getElementById('successModal').style.display = 'none';
            }, 3000);
        });
    </script>
</div>

Make sure to replace the modal markup and JavaScript with whatever is appropriate for the modal system you're using. The example above uses plain JavaScript and a simple modal for demonstration purposes.

This approach allows you to show a flash message in a modal without redirecting the user, and it leverages Livewire's ability to communicate between the server-side component and the client-side JavaScript.

valentin_vranic's avatar
Level 5

I found the solution:

$this->dispatch('success', message: "Post updated successfully!");

On blade side:

<div x-data="{ open: false, message: ''}" @success.window="open = true; message=$event.detail.message">
    <div
        x-show="open"
        x-text="message"
        class="alert alert-success">
    </div>
</div>

Please or to participate in this conversation.