Courses

Livewire 3 From Scratch: Practical Course

Delete Table Data with Confirmation Prompt

Summary of this lesson:
- Adding delete functionality
- Implementing confirmation prompts
- Managing event propagation
- Using wire:click with confirmation

In this lesson, let's see how to add a confirmation prompt before deleting a record.

delete confirmation


So first, let's add a method to the Livewire component and a wire:click directive to the delete button to trigger that method.

app/Livewire/Products.php:

class Products extends Component
{
// ...
 
public function deleteProduct(int $productId): void
{
Product::where('id', $productId)->delete();
}
 
// ...
}

resources/views/livewire/products.blade.php:

<div class="space-y-6">
// ...
<td>
<a href="#" class="inline-flex items-center px-4 py-2 bg-gray-800 rounded-md font-semibold text-xs text-white uppercase tracking-widest">
Edit </a>
<a wire:click="deleteProduct({{ $product->id }})" href="#" class="inline-flex items-center px-4 py-2 bg-red-600 rounded-md font-semibold text-xs text-white uppercase tracking-widest"> // [tl! highlight]
Delete </a>
</td>
// ...
</div>

If you would try to delete any record, it would be successful.

Let's add an onlick event for a confirmation prompt.

resources/views/livewire/products.blade.php:

<div class="space-y-6">
// ...
<td>
<a href="#" class="inline-flex items-center px-4 py-2 bg-gray-800 rounded-md font-semibold text-xs text-white uppercase tracking-widest">
Edit </a>
<a wire:click="deleteProduct({{ $product->id }})" onclick="return confirm('Are you sure?') || event.stopImmediatePropagation()" href="#" class="inline-flex items-center px-4 py-2 bg-red-600 rounded-md font-semibold text-xs text-white uppercase tracking-widest"> // [tl! highlight]
Delete </a>
</td>
// ...
</div>

The important part of this event is the event.stopImmediatePropagation(). If we don't add it, then even if you cancel the prompt, the wire:click action will still be triggered.

delete confirmation

Previous: wire:loading Indicator
avatar
Orpheric Florent Allagbe (Orpheric_Codeur)

Interesting functionality for adding a dialog box. You can also achieve the same result and even customize a password before the confirmation runs with Livewire's new "wire:confirm" feature. More info here: https://livewire.laravel.com/docs/wire-confirm

👍 1
avatar

Yes you can. This feature was added a couple months after this course was released.

avatar
You can use Markdown
avatar

why is it deleted only for the first time, but it can't be deleted any further

avatar

Can you expand on this? Not sure what you have in mind here.

avatar

in general, it deletes only once

avatar

pass id at the view and class

avatar
You can use Markdown
avatar
You can use Markdown