i'm try to use sweetalert2 in livewire - Instead of deleting one post, all posts will be deleted what is my problem?
post.list.blade
<button wire:click="deleteConfirm" type="button">delete</button>
component
public function deleteConfirm(){$this->emit('swal', 'are u sure?', 'warning');}
and
public function delete(){$this->post->delete();}
my js:
const Swal = Swal.mixin({
position: 'center',
showConfirmButton: true,
})
document.addEventListener('livewire:load', () => {
Livewire.on('swal', (message,type) => {
Swal.fire({
icon: type,
text: message,
showCancelButton: true,
}).then((result) => {
if (result.isConfirmed) {
livewire.emit('delete')
}
})
})
})
normally, when you have a list of elements with actions like edit, details, delete, etc. you must pass the item id to the action.
post.list.blade
<button wire:click="deleteConfirm({{ $item->id }})" type="button">delete</button>
component
public function deleteConfirm($item_id)
{
$this->post = Post::where('id',$item_id)->first();
$this->emit('swal', 'are u sure?', 'warning');
}
and
public function delete()
{
if($this->post) {
$this->post->delete();
$this->post = null;
}
}