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:
- 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!']);
}
}
- In your Blade template, listen for the
show-success-messageevent 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.