Toast Notification in Laravel Livewire Tutorial - TechvBlogs

Toast Notification in Laravel Livewire Tutorial

A toast notification is a message object that presents timely information, including confirmation of actions, alerts, and errors.


Suresh Ramani - Author - TechvBlogs
Suresh Ramani
 

2 years ago

TechvBlogs - Google News

What is Livewire?

Livewire is a full-stack framework for Laravel that makes building dynamic interfaces simple, without leaving the comfort of Laravel. Livewire relies solely on AJAX requests to do all its server communications. Livewire completely sends Ajax requests to do all its server-side communication without writing any line of Ajax script.

What is Toast Notification?

toast notification is a message object that presents timely information, including confirmation of actions, alerts, and errors.

In most projects, We are use sweetalert2 for toast notifications. Sweetalert2 is very easy to use and implements in any frontend frameworks like Vue.js, React.js and etc.

We have already a project of Laravel Livewire Crud Example. so in this blog, we don't need to create a project for this example. Let's start with some basic steps.

Step 1: Clone Project

git clone https://github.com/suresh-ramani/larawire-crud-app.git

Step 2: Install Project Dependency

composer install

Step 3: Setup Database Detail

DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=<DATABASE NAME>
DB_USERNAME=<DATABASE USERNAME>
DB_PASSWORD=<DATABASE PASSWORD>

Step 4: Add Sweetalert2 script to home.blade.php

Put this toast notification code under @livewireScripts

<script src="//cdn.jsdelivr.net/npm/sweetalert2@10"></script>
<script>
    const Toast = Swal.mixin({
        toast: true,
        position: 'top',
        showConfirmButton: false,
        showCloseButton: true,
        timer: 5000,
        timerProgressBar:true,
        didOpen: (toast) => {
            toast.addEventListener('mouseenter', Swal.stopTimer)
            toast.addEventListener('mouseleave', Swal.resumeTimer)
        }
    });

    window.addEventListener('alert',({detail:{type,message}})=>{
        Toast.fire({
            icon:type,
            title:message
        })
    })
</script>

Read Also: Generate Temporary Signed URL from s3 in Laravel

Step 5: Dispatch Event From Livewire Component

Livewire allows firing browser window events from components.

<?php

namespace App\Http\Livewire;

use Livewire\Component;
use App\Models\Category as Categories;

class Category extends Component
{
    public $categories, $name, $description, $category_id;
    public $updateCategory = false;

    protected $listeners = [
        'deleteCategory'=>'destroy'
    ];

    // Validation Rules
    protected $rules = [
        'name'=>'required',
        'description'=>'required'
    ];

    public function render()
    {
        $this->categories = Categories::select('id','name','description')->get();
        
        return view('livewire.category');
    }

    public function resetFields(){
        $this->name = '';
        $this->description = '';
    }

    public function store(){
        // Validate Form Request
        $this->validate();

        try{
            // Create Category
            Categories::create([
                'name'=>$this->name,
                'description'=>$this->description
            ]);
    
            // Set Flash Message
            $this->dispatchBrowserEvent('alert',[
                'type'=>'success',
                'message'=>"Category Created Successfully!!"
            ]);

            // Reset Form Fields After Creating Category
            $this->resetFields();
        }catch(\Exception $e){
            // Set Flash Message
            $this->dispatchBrowserEvent('alert',[
                'type'=>'error',
                'message'=>"Something goes wrong while creating category!!"
            ]);

            // Reset Form Fields After Creating Category
            $this->resetFields();
        }
    }

    public function edit($id){
        $category = Categories::findOrFail($id);
        $this->name = $category->name;
        $this->description = $category->description;
        $this->category_id = $category->id;
        $this->updateCategory = true;
    }

    public function cancel()
    {
        $this->updateCategory = false;
        $this->resetFields();
    }

    public function update(){

        // Validate request
        $this->validate();

        try{

            // Update category
            Categories::find($this->category_id)->fill([
                'name'=>$this->name,
                'description'=>$this->description
            ])->save();

            $this->dispatchBrowserEvent('alert',[
                'type'=>'success',
                'message'=>"Category Updated Successfully!!"
            ]);
    
            $this->cancel();
        }catch(\Exception $e){
            $this->dispatchBrowserEvent('alert',[
                'type'=>'error',
                'message'=>"Something goes wrong while updating category!!"
            ]);
            $this->cancel();
        }
    }

    public function destroy($id){
        try{
            Categories::find($id)->delete();
            $this->dispatchBrowserEvent('alert',[
                'type'=>'success',
                'message'=>"Category Deleted Successfully!!"
            ]);
        }catch(\Exception $e){
            $this->dispatchBrowserEvent('alert',[
                'type'=>'success',
                'message'=>"Something goes wrong while deleting category!!"
            ]);
        }
    }
}

Step 6: Run Project

Now all are set to go, open a terminal and run the following command into your terminal.

php artisan serve

It'd be a good idea to follow along with the simple demo app that can be found in this GitHub repo.

Read Also: Build Crud App with Laravel and Vue.js

 

Comments (2)

aman aman 1 year ago

Toaster is aligned in center i need in top right side

Suresh Ramani Suresh Ramani 1 year ago

You can follow this link https://sweetalert2.github.io/#position

Comment


Note: All Input Fields are required.