How to make alerts or confirmation dialogs in Laravel Livewire

- Andrés Cruz

En español
How to make alerts or confirmation dialogs in Laravel Livewire

A confirmation dialog is nothing more than a dialog box that is displayed in the browser to confirm an action to be performed in a web application. For example, if a user clicks a button that deletes a record in a table, a confirmation dialog can be displayed asking the user if he is sure that he wants to delete the record. Let's see how to implement one in Livewire.

Laravel Livewire is great, performing operations that require both sides, that is, the client and the server are always heavy since we have to create rest apis, and connect both entities, or from vanilla JavaScript, send fetch requests, return json, evaluate answer, make changes to the html... a real mess and a lot of work to make updates; Livewire abstracts us from all this using events and functions, as well as a base structure to be able to communicate between the client and the server in a very direct way.

The problem is that this facility sometimes makes us inflexible, and performing simple operations such as deleting, are too simple and direct with livewire; usually we have in Livewire something like:

<x-a-danger wire:click="delete({{ $p }})" href="#">

In practice, if we click on the HTML element that has said attribute defined, it DELETES THE ELEMENT FROM ONE, which you probably won't want because our user may mistakenly click on that option; for deletions it is good practice to place a confirmation dialog; so, to avoid deleting records with a single click, on the same element that contains the wire:click, you can place a JavaScript onclick with said confirmation dialog:

<x-a-danger onclick="confirm('¿Seguro que quieres eliminar?') || event.stopImmediatePropagation()"  wire:click="delete({{ $p }})" href="#">

The key here is the stopImmediatePropagation which stops the scheduling of the event; livewire at its core uses events on the client to call events on the server, JavaScript events that we can also stop.

Andrés Cruz

Desarrollo con Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz en Udemy

Acepto recibir anuncios de interes sobre este Blog.