How To Create Livewire Sweetalert In Laravel 10

As a web developer, I understand the importance of providing a delightful user experience on my projects. That's why I'm excited to explore the integration of SweetAlert, a popular library for creating visually appealing and interactive alert dialogs, with Laravel's Livewire framework.

In this article, I'll guide you through the process of seamlessly implementing Livewire SweetAlert in your Laravel 10 projects. With SweetAlert, I can easily display captivating success messages, error alerts, and even gather user input through modals, all without the need for complex JavaScript code.

Together, we'll take a step-by-step approach to setting up Livewire SweetAlert in my Laravel 10 application. Whether you're looking to implement basic alert messages or more sophisticated custom modals, SweetAlert in Livewire will empower you to create engaging interactions that leave a lasting impression on your users.

By the end of this tutorial, you'll have the know-how to harness the combined power of Livewire and SweetAlert, elevating the interactivity and user experience of your Laravel 10 application.

So, if you're as eager as I am to make my application stand out with visually stunning and user-friendly alerts, let's dive into the magic of Livewire SweetAlert in Laravel 10 together.

 Step 1: Install Laravel 10

If you don't have a Laravel project set up, create one using Composer.

composer create-project --prefer-dist laravel/laravel sweetalert_example

 

Step 2: Install Livewire

Install Livewire using Composer.

composer require livewire/livewire

 

Step 3: Create a New Livewire Component

Generate a new Livewire component using the Artisan command.

php artisan make:livewire SweetAlertExample

Open the newly created SweetAlertExample.php file located at app/Http/Livewire. Update the render() method with the following code.

<?php
  
namespace App\Http\Livewire;
  
use Livewire\Component;
  
class SweetAlertExample extends Component
{
  
    protected $listeners = ['remove'];
  
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function render()
    {
        return view('livewire.sweet-alert-example')->extends('layouts.app');
    }
  

    public function alertSuccess()
    {
        $this->dispatchBrowserEvent('swal:modal', [
                'type' => 'success',  
                'message' => 'User Created Successfully!', 
                'text' => 'It will list on the users table soon.'
            ]);
    }
  
    public function alertConfirm()
    {
        $this->dispatchBrowserEvent('swal:confirm', [
                'type' => 'warning',  
                'message' => 'Are you sure?', 
                'text' => 'If deleted, you will not be able to recover this item!'
            ]);
    }
  
    
    public function remove()
    {        
        $this->dispatchBrowserEvent('swal:modal', [
                'type' => 'success',  
                'message' => 'User Delete Successfully!', 
                'text' => 'It will not list on the users table soon.'
            ]);
    }
}

 

 

Step 4: Create the Livewire Blade View

Create a new Blade view file named sweet-alert-example.blade.php in the resources/views/livewire directory. Add the following content to the Blade view file.

<div>
    <h1>Laravel 10 Livewire Sweetalert Example - Techsolutionstuff</h1>
    <button type="button" wire:click="alertSuccess" class="btn btn-success">Success Alert</button>
    <button type="button" wire:click="alertConfirm" class="btn btn-danger">Confirm Box</button>
</div>

 

 Step 5: Create Route

In this step, we will add routes to the web.php file.

routes/web.php

<?php
  
use Illuminate\Support\Facades\Route;
 
use App\Http\Livewire\SweetAlertExample;
  
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
  
Route::get('sweetalert-notification', SweetAlertExample::class);

 

Step 6: Include the Livewire Component

In this step, we will create a blade file and include @livewireStyles, and @livewireScripts.

resources/views/layouts/app.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>How to create sweetalert in laravel 10 using livewire - techsolutionstuff</title>
    @livewireStyles
    <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
    <script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
    <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
</head>
<body>
    
<div class="container">
    @yield('content')
</div>
    
</body>
  
@livewireScripts
  
<script>
  
window.addEventListener('swal:modal', event => { 
    swal({
      title: event.detail.message,
      text: event.detail.text,
      icon: event.detail.type,
    });
});
  
window.addEventListener('swal:confirm', event => { 
    swal({
      title: event.detail.message,
      text: event.detail.text,
      icon: event.detail.type,
      buttons: true,
      dangerMode: true,
    })
    .then((willDelete) => {
      if (willDelete) {
        window.livewire.emit('remove');
      }
    });
});
 </script>
  
</html>

 

Step 7: Start the Development Server and Test

Start the Laravel development server by running the command.

php artisan serve

Open your browser and visit local URL. Click the "Show SweetAlert" button, and you should see a success message from SweetAlert.

Congratulations! You have successfully created Livewire SweetAlert in your Laravel 10 project using CDN files. Now, you can easily enhance user interactions by adding visually appealing and interactive alert dialogs to your application.

 


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS