Ajax Autocomplete search from database in Laravel 11

 <?php


namespace App\Http\Controllers;

use App\Models\Product;
use Illuminate\Http\Request;

class SearchController extends Controller
{
    public function productSearching(Request $request)
    {
        if ($request->ajax()) {
            $data = Product::where("name", "LIKE", $request->name . "%")->get();
            $output = "";
            if (count($data) > 0) {
                $output = "<ul class='list-group' style='display:block;position:relative;z-index:1'>";
                foreach ($data as $row) {
                    $output .= "<li class='list-group-item'>" . $row->name . "</li>";
                }
                $output .= "</ul>";
            } else {
                $output = "<li class='list-group-item'>No Data Found</li>";
            }
            return $output;
        }
        return view("product");
    }
}
Above File is app\Http\Controllers\SearchController.php File





Below File is app\Models\Product.php File
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    public $timestamps = true;
    protected $table = "products";
    protected $fillable = ["name"];
}






Below File is database\json\products.json File
[
    {
        "name": "Shoes"
    },
    {
        "name": "Sandals"
    },
    {
        "name": "Soap"
    },
    {
        "name": "Bags"
    },
    {
        "name": "Earnings"
    },
    {
        "name": "Shirts"
    },
    {
        "name": "Pants"
    },
    {
        "name": "Scarf"
    },
    {
        "name": "T-shirt"
    },
    {
        "name": "Hair dryer"
    },
    {
        "name": "Lipstick"
    }
]





Below File is database\migrations\2025_01_02_133958_create_products_table File
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string("name");
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('products');
    }
};





Below File is database\seeeders\DatabaseSeeder.php File
<?php

namespace Database\Seeders;

use App\Models\User;
// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     */
    public function run(): void
    {
        // User::factory(10)->create();

        // User::factory()->create([
        //     'name' => 'Test User',
        //     'email' => 'test@example.com',
        // ]);

        $this->call([
            ProductSeeder::class
        ]);
    }
}





Below File is database\seeders\ProductSeeder.php File
<?php

namespace Database\Seeders;

use App\Models\Product;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\File;

class ProductSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $json = File::get(path: "database/json/products.json");
        $product = collect(json_decode($json));

        $product->each(function ($product) {
            Product::create([
                "name" => $product->name
            ]);
        });
    }
}





Below File is resources\views\product.blade.php File
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Searching</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
</head>
<body>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-10">
                <div class="card">
                    <div class="card-header">
                        <h2>Product Name</h2>
                    </div>
                    <div class="card-body">
                        <input type="text" name="name" class="form-control" id="name" placeholder="Search product name"/>
                        <div id="product_list"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        $(document).ready(function(){
            $("#name").on("keyup",function(){
                var value = $(this).val();
                $.ajax({
                    url:"{{ route('search') }}",
                    type:"GET",
                    data:{"name":value},
                    success:function(data){
                        $("#product_list").html(data);
                    },
                });
            });

            $(document).on("click","li",function(){
                var value = $(this).text();
                $("#name").val(value);
                $("#product_list").html("");
            });
        });
    </script>
</body>
</html>





Below File is routes\web.php File
<?php

use App\Http\Controllers\SearchController;
use Illuminate\Support\Facades\Route;

Route::get('/', function () {
    return view('welcome');
});

Route::controller(SearchController::class)->group(function () {
    Route::get("/search", "productSearching")->name("search");
});









Comments

Popular posts from this blog

Eloquent Many to Many Relationship Tutorial in Laravel 11

Eloquent with JSON Data Columns Tutorial in Laravel 11

Blade Template Tutorial Three Template Inheritance in Laravel 11