DEV Community

Cover image for How to use SweetAlert2 with Livewire
Rashid Ali
Rashid Ali

Posted on

How to use SweetAlert2 with Livewire

I got too many requests for adding confirmation alerts feature to realrashid/sweet-alert package this 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 package with the help of Livewire šŸŽ‰

So without any further due Let's Begin šŸ”„

First Install the realrashid/sweet-alert package in your project if not installed yet šŸ˜¢

composer require realrashid/sweet-alert
Enter fullscreen mode Exit fullscreen mode

Then configure the package.

Include 'sweetalert::alert' view in master layout

@include('sweetalert::alert')
Enter fullscreen mode Exit fullscreen mode

and run the below command to publish the package assets.

php artisan sweetalert:publish
Enter fullscreen mode Exit fullscreen mode

Yahoooooooo You Have Successfully Installed realrashid/sweet-alert šŸ˜‰

For more info checkout the documentation.
sweet-alert/documentation šŸ“˜

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 package with Livewire šŸŽ‰ šŸŽ‰

Now let's install the Livewire then we go further šŸ˜Ž .

composer require livewire/livewire
Enter fullscreen mode Exit fullscreen mode

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')

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

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

Now let's create a Livewire ConfirmAlert component.

php artisan make:livewire ConfirmAlert 
Enter fullscreen mode Exit fullscreen mode

Running this above command will generate the following two files:

// app/Http/Livewire/ConfirmAlert.php
// resources/views/livewire/confirm-alert.blade.php
Enter fullscreen mode Exit fullscreen mode

Let's first start with app/Http/Livewire/ConfirmAlert.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();
    }
}

Enter fullscreen mode Exit fullscreen mode

Now Let's edit the component view!

<!-- 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
Enter fullscreen mode Exit fullscreen mode

You did it šŸŽ‰

Now just load the button within your blade.
In my case it is resources/views/contacts/index.blade.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>
Enter fullscreen mode Exit fullscreen mode

That's it.

Thank you! šŸ‘

Top comments (4)

Collapse
 
vitoo profile image
Victorien Plancke • Edited

Yes, you can also emit the event from the component :

$this->emit('message', 'Your profile has been updated.');

And listen to it in JS :

    Livewire.on('message', message =&gt; {
        alert(message); //put sweet alert here :)
    })
Enter fullscreen mode Exit fullscreen mode
Collapse
 
snehalkadwe profile image
Snehal Rajeev Moon

Yes we can do that. Thank you šŸ™‚šŸ™‚

Collapse
 
diogolf profile image
diogolf • Edited

Hi, can you give me a real example with a simple success alert or toast message ?
Thank you

Thread Thread
 
snehalkadwe profile image
Snehal Rajeev Moon

Sure, I will make one.