Reputation: 1
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!');
}
Upvotes: -1
Views: 1517
Reputation: 26460
I would say that you are better off dispatching a browser-event and listening for that in JavaScript, rather than using sessions. Sessions can be a bit tricky between requests, since Livewire is in effect a stateless API.
When using dispatchBrowserEvent()
, you can pass in data as the second argument, which will be available in the event.detail
property of the event.
public function delete($id)
{
$categoriesService = CategoriesService::deleteCategory($id);
if (!$categoriesService) {
$swalData = [
'type' => 'error',
'title' => 'Error',
'message' => 'Failed to delete category',
];
} else {
$swalData = [
'type' => 'success',
'title' => 'Success',
'message' => 'Sucessfully deleted category',
];
}
$this->dispatchBrowserEvent('notify-swal', $swalData);
}
And then - once in your blade (would suggest maybe in your layout, that way its reusable across all components), add a listener for that event.
@once
<script>
window.addEventListener('notify-swal', function(e) {
let data = e.detail;
let title = data.title;
let message = data.message;
let type = data.type;
Swal.fire(title, message, type);
});
</script>
@endonce
Upvotes: 1
Reputation: 2352
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>
Upvotes: 1