Toast Notification in Laravel Livewire Tutorial

Toast Notification in Laravel Livewire Tutorial

In this post we will give you information about Toast Notification in Laravel Livewire Tutorial. Hear we will give you detail about Toast Notification in Laravel Livewire Tutorial And how to use it also give you demo for it if it is necessary.

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/[email protected]"></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>

Also see: 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 AppHttpLivewire;

use LivewireComponent;
use AppModelsCategory 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.

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

 

Hope this code and post will helped you for implement Toast Notification in Laravel Livewire Tutorial. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US