Finally in this section, we take care of deleting the category. You would say there is nothing to do with Livewire here, but what about the confirmation?
Before deleting the category, we will ask for confirmation, but for that, we will use sweetalert2. First, for the popup.
resources/views/layouts/app.blade.php:
@livewireScripts <script src="https://unpkg.com/@nextapps-be/livewire-sortablejs@0.2.0/dist/livewire-sortable.js"></script> <script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script> <script> document.addEventListener('livewire:init', () => { Livewire.on('swal:confirm', (event) => { swal.fire({ title: event[0].title, text: event[0].text, icon: event[0].type, showCancelButton: true, confirmButtonColor: 'rgb(239 68 6)', confirmButtonText: 'Yes, delete it!' }) .then((willDelete) => { if (willDelete.isConfirmed) { Livewire.dispatch(event[0].method, { id: event[0].id }); } }); }) }); </script> </body></html>
Here we add sweetalert from CDN. Then, we add an event listener. That event will be fired from Livewire Component. When this event will be fired, a sweetalert popup will be shown, and after confirmation, event will be fired to the Livewire component to delete the category.
Now, we need to add the wire:click
action to the Delete button.
<button wire:click="deleteConfirm('delete', {{ $category->id }})" class="px-4 py-2 text-xs text-red-500 uppercase bg-red-200 rounded-md border border-transparent hover:text-red-700 hover:bg-red-300"> Delete</button>
After clicking the Delete button, Livewire will send an event which will show the sweetaler2 popup.
app/Livewire/CategoriesList.php:
class CategoriesList extends Component{ // ... public function deleteConfirm(string $method, $id = null): void { $this->dispatch('swal:confirm', [ 'type' => 'warning', 'title' => 'Are you sure?', 'text' => '', 'id' => $id, 'method' => $method, ]); }}
After confirming deletion, the delete
event is fired. We need to add a listener to the Livewire component which will catch that event and just deletes the category.
use Livewire\Attributes\On; class CategoriesList extends Component{ // ... #[On('delete')] public function delete($id) { Category::findOrFail($id)->delete(); }}
And, that's it for the Categories CRUD, with a lot of dynamic behavior.
Liked it? Let's move on to other features!