article

Thursday, July 7, 2022

Laravel 9 Live search using Jquery AJAX

Laravel 9 Live search using Jquery AJAX

How to install laravel 9

https://tutorial101.blogspot.com/2022/02/how-to-install-laravel-9.html

Connecting our Database

open .env file root directory.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laraveldb
DB_USERNAME=root
DB_PASSWORD=

Create tables 

php artisan make:migration create_customers_table
C:\xampp\htdocs\laravel\laravelproject>php artisan make:migration create_customers_table


Open new migrations
yourproject/database/migrations
laravelproject\database\migrations\create_customers_table.php
//laravelproject\database\migrations\create_customers_table.php
return new class extends Migration
{
    public function up()
    {
        Schema::create('customers', function (Blueprint $table) {
            $table->id();
            $table->string('CustomerName');
            $table->string('Address');
            $table->string('City');
            $table->string('PostalCode');
            $table->string('Country');
            $table->timestamps();
        });
    }
};
Database Migration
php artisan migrate

C:\xampp\htdocs\laravel\laravelproject>php artisan migrate
Migration table created successfully.
check database table

Create tables Model

php artisan make:model Customers

Creating Controller

php artisan make:controller LiveSearchController
C:\xampp\htdocs\laravel\laravelproject>php artisan make:controller LiveSearchController
change it with the following codes:
laravelproject\app\Http\Controllers\LiveSearchController.php
//laravelproject\app\Http\Controllers\LiveSearchController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;

class LiveSearchController extends Controller
{
    function index()
    {
        return view('livesearch');
    }

    function action(Request $request)
    {
        if($request->ajax())
        {
            $output = '';
            $query = $request->get('query');
            if($query != '') {
                $data = DB::table('customers')
                    ->where('CustomerName', 'like', '%'.$query.'%')
                    ->orWhere('Address', 'like', '%'.$query.'%')
                    ->orWhere('City', 'like', '%'.$query.'%')
                    ->orWhere('PostalCode', 'like', '%'.$query.'%')
                    ->orWhere('Country', 'like', '%'.$query.'%')
                    ->orderBy('id', 'desc')
                    ->get();
                   
            } else {
                $data = DB::table('customers')
                    ->orderBy('id', 'desc')
                    ->get();
            }
            
            $total_row = $data->count();
            if($total_row > 0){
                foreach($data as $row)
                {
                    $output .= '
                    <tr>
                    <td>'.$row->CustomerName.'</td>
                    <td>'.$row->Address.'</td>
                    <td>'.$row->City.'</td>
                    <td>'.$row->PostalCode.'</td>
                    <td>'.$row->Country.'</td>
                    </tr>
                    ';
                }
            } else {
                $output = '
                <tr>
                    <td align="center" colspan="5">No Data Found</td>
                </tr>
                ';
            }
            $data = array(
                'table_data'  => $output,
                'total_data'  => $total_row
            );
            echo json_encode($data);
        }
    }
}
Route
laravelproject\routes\web.php
//laravelproject\routes\web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\LiveSearchController; //add LiveSearchController

//Route::get('/', function () {
//    return view('welcome');
//});
  
Route::get('/', [LiveSearchController::class, 'index']);
Route::get('/action', [LiveSearchController::class, 'action'])->name('action');
Create Views
laravelproject\resources\views\livesearch.blade.php

Bootstrap 5 https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js
//laravelproject\resources\views\livesearch.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Laravel 9 Live search using Jquery AJAX</title>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" />
</head>
<body>
<div class="container">
    <h3 align="center">Laravel 9 Live search using Jquery AJAX</h3><br />
    <div class="row">
    <h2>Search Customer Total Data : <span id="total_records"></span></h2>
    <div class="col-12">
        <div class="form-group">
            <input type="text" name="search" id="search" class="form-control" placeholder="Search Customer Data" />
        </div>
        <div class="table-responsive">
            <table class="table table-striped table-bordered">
            <thead>
                <tr>
                <th>Customer Name</th>
                <th>Address</th>
                <th>City</th>
                <th>Postal Code</th>
                <th>Country</th>
                </tr>
            </thead>
            <tbody></tbody>
            </table>
        </div>
    </div>    
    </div>
</div>
<script>
$(document).ready(function(){

    fetch_customer_data();

    function fetch_customer_data(query = '')
    {
        $.ajax({
            url:"{{ route('action') }}",
            method:'GET',
            data:{query:query},
            dataType:'json',
            success:function(data)
            {
                $('tbody').html(data.table_data);
                $('#total_records').text(data.total_data);
            }
        })
    }

    $(document).on('keyup', '#search', function(){
        var query = $(this).val();
        fetch_customer_data(query);
    });
});
</script>
</body>
</html>
Run C:\xampp\htdocs\laravel\laravelproject>php artisan serve
Starting Laravel development server: http://127.0.0.1:8000

Related Post