How to use SweetAlert2 with Livewire
Tags: php, laravel, livewire, sweetalert2
Published: 2021-02-17 18:01:58

I got too many requests for adding confirmation alerts feature to [realrashid/sweet-alert](https://github.com/realrashid/sweet-alert) package this [realrashid/sweet-alert/issues/57](https://github.com/realrashid/sweet-alert/issues/57) is one of the earliest request for adding confirmation alerts feature but unfortunately i haven't added this feature yet because i haven't found the best way to achieve this.


So Today I found an easy way to do this without adding the support for this feature in [realrashid/sweet-alert](https://github.com/realrashid/sweet-alert) package with the help of [Livewire](https://laravel-livewire.com/) :tada:

So without any further due Let's Begin :fire:

First Install the [realrashid/sweet-alert](https://github.com/realrashid/sweet-alert) package in your project if not installed yet :cry:

```bash
composer require realrashid/sweet-alert
```
Then configure the package.

Include `'sweetalert::alert'` view in master layout
 
```php
@include('sweetalert::alert')
```

and run the below command to publish the package assets.

```bash
php artisan sweetalert:publish
```

Yahoooooooo You Have Successfully Installed [realrashid/sweet-alert](https://github.com/realrashid/sweet-alert) :wink:

For more info checkout the documentation.
[sweet-alert/documentation](https://realrashid.github.io/sweet-alert) :blue_book:

**Note:** You have to enable `SWEET_ALERT_ALWAYS_LOAD_JS` in your `.env` file!

Like this `SWEET_ALERT_ALWAYS_LOAD_JS=true`.

Congratulations now you can use the [realrashid/sweet-alert](https://github.com/realrashid/sweet-alert) package with [Livewire](https://laravel-livewire.com/) :tada: :tada:

Now let's install the [Livewire](https://laravel-livewire.com/) then we go further :sunglasses: .

```bash
composer require livewire/livewire
```

Include the JavaScript (on every page that will be using Livewire).

In our case this is our master layout there we included `@include('sweetalert::alert')`

```php
...
    @livewireStyles
</head>
<body>
    ...

    @include('sweetalert::alert')
    @livewireScripts
    // Don't forget the stack tag!
    @stack('scripts')
</body>
</html>
```

Now let's create a Livewire ConfirmAlert component.

```bash
php artisan make:livewire ConfirmAlert 
```
Running this above command will generate the following two files:

```php
// app/Http/Livewire/ConfirmAlert.php
// resources/views/livewire/confirm-alert.blade.php
```

Let's first start with `app/Http/Livewire/ConfirmAlert.php`

```php
<?php

namespace App\Http\Livewire;

use Livewire\Component;
use App\Contact;

class ConfirmDelete extends Component
{
    /**
     * Contact Id
     *
     * @var [inf]
     */
    public $contactId;

    /**
     * Render the confirm-alert button
     * @return view
     * @author Rashid Ali <realrashid05@gmail.com>
     */
    public function render()
    {
        return view('livewire.confirm-delete');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     * @author Rashid Ali <realrashid05@gmail.com>
     */
    public function destroy($contactId)
    {
        Contact::find($contactId)->delete();
    }
}

```
Now Let's edit the component view!

```php
<!-- resources/views/livewire/confirm-alert.blade.php -->

<div>
    <button class="btn btn-danger" wire:click="$emit('triggerDelete',{{ $contactId }})">
        Delete
    </button>
</div>

@push('scripts')
<script type="text/javascript">
    document.addEventListener('DOMContentLoaded', function () {
        @this.on('triggerDelete', contactId => {
            Swal.fire({
                title: 'Are You Sure?',
                text: 'Conatct record will be deleted!',
                icon: "warning",
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#aaa',
                confirmButtonText: 'Delete!'
            }).then((result) => {
		 //if user clicks on delete
                if (result.value) {
		     // calling destroy method to delete
                    @this.call('destroy',contactId)
		     // success response
                    Swal.fire({title: 'Contact deleted successfully!', icon: 'success'});
                } else {
                    Swal.fire({
                        title: 'Operation Cancelled!',
                        icon: 'success'
                    });
                }
            });
        });
    })
</script>
@endpush
```

You did it :tada:

Now just load the button within your blade.
In my case it is `resources/views/contacts/index.blade.php`.

```php
<table class="table table-striped">
    <thead>
        <tr>
            <td>....</td>
            <td colspan=2>Actions</td>
        </tr>
    </thead>
    <tbody>
        @foreach($contacts as $contact)
        <tr>
            <td>...</td>
            <td>
                <a href="...">Edit</a>
            </td>
            <td>
                @livewire('confirm-delete', ['contactId' => $contact->id])
            </td>
        </tr>
        @endforeach
    </tbody>
</table>
```

That's it.

Thank you! :+1: