I have a problem when trying to show a flash message with Livewire navigate and toastr. If I use normal redirect without navigate, It works as normal with the code below.
$url = route('role.detail', 5);
session()->flash('success', config('app.success'));
return redirect($url);
But when I change my code to use Livewire navigate, the flash message not showing with toastr.
$url = route('role.detail', 5);
session()->flash('success', config('app.success'));
return $this->redirect($url, navigate: true);
I also try to dispatch as well, but it also not working.
$url = route('role.detail', 5);
$this->dispatch('success',['message'=>config('app.success')]);
return $this->redirect($url, navigate: true);
Is there any way that I can flash message when redirect with Livewire naviage? And below is my toastr code for showing flash message.
<script>
$(document).ready(function(){
toastr.options = {
"closeButton": true,
"debug": false,
"newestOnTop": false,
"progressBar": true,
"positionClass": "toast-top-right",
"preventDuplicates": false,
"onclick": null,
"showDuration": "300",
"hideDuration": "500",
"timeOut": "5000",
"extendedTimeOut": "1000",
"showEasing": "swing",
"hideEasing": "linear",
"showMethod": "fadeIn",
"hideMethod": "fadeOut"
};
window.addEventListener('success', event=>{
toastr.remove();
toastr.success(event.detail[0].message);
});
window.addEventListener('error', event=>{
toastr.remove();
toastr.error(event.detail[0].message);
});
});
@if(Session::has('success'))
window.onload = function(){
toastr.remove();
toastr.success("{{session('success')}}");
};
@endif
@if(Session::has('error'))
window.onload = function(){
toastr.remove();
toastr.error("{{session('error')}}");
};
@endif
</script>
Livewire session-based flash messages are not automatically preserved across navigation. You could use Livewire’s events to manually display flash messages or pass the message as part of the navigation.
- Using events:
Use dispatch() to initiate event:
$url = route('role.detail', 5);
$this->dispatch('showFlashMessage', ['type' => 'success', 'message' => config('app.success')]);
return $this->redirect($url, navigate: true);
And in your blade, use this to listen for the given event:
<div>
<script>
Livewire.on('showFlashMessage', ({type, message}) => {
alert(`${type}: ${message}`);
});
</script>
</div>
Read more about events here.
- Passing the message as part of the navigation
Add message param to your url:
$url = route('role.detail', ['id' => 5, 'flash_message' => config('app.success')]);
return $this->redirect($url, navigate: true);
Inside your mount() method, retrieve the param:
if (request()->has('flash_message')) {
$this->dispatch('showFlashMessage', [
'type' => 'success',
'message' => request('flash_message')
]);
}
And then display it like this:
<div>
<script>
Livewire.on('showFlashMessage', ({type, message}) => {
alert(`${type}: ${message}`);
});
</script>
</div>
1