article

Thursday, May 25, 2023

React JS Laravel 10 AutoComplete Textbox | Filter Search

React JS Laravel 10 AutoComplete Textbox | Filter Search

Download Laravel App

composer create-project --prefer-dist laravel/laravel my-app
C:\xampp\htdocs\laravel10project>composer create-project laravel/laravel laravel10project

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 Model and Migration

C:\xampp\htdocs\laravel\laravelproject>php artisan make:model Country -m

A new file named Country.php will be created in the app directory and database/migrations directory to generate the table in our database
app/Models/Country.php

//app/Models/Country.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Country extends Model
{
    use HasFactory;

    protected $fillable = [
        'countryName'
    ];
}
database\migrations\create_countries_table.php
//database\migrations\create_countries_table.php
<?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('countries', function (Blueprint $table) {
            $table->id();
            $table->string('countryName');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('countries');
    }
};
Database Migration
php artisan migrate

C:\xampp\htdocs\laravel\laravel10project>php artisan migrate
Migration table created successfully.

check database table
br/> Create Controller
C:\xampp\htdocs\laravel\laravel10project>php artisan make:controller AutoCompleteController

app\Http\Controllers\AutoCompleteController.php
//app\Http\Controllers\AutoCompleteController.php
<?php

namespace App\Http\Controllers;

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

class AutoCompleteController extends Controller
{
    public function index()
    {
       $countries = Country::all(); 
	   
       // Return Json Response
       return response()->json([
            'results' => $countries
       ],200);
    }
}
routes/api.php
//
<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AutoCompleteController;

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

Route::get('autocomplete', [AutoCompleteController::class, 'index']); 
Run C:\xampp\htdocs\laravel\laravel10project>php artisan serve
Starting Laravel development server: http://127.0.0.1:8000/autocomplete

React JS
https://create-react-app.dev/

Create Project
C:\react-js>npx create-react-app myreactdev

Run
C:\react-js\myreactdev> npm start

C:\react-js\myreactdev\src\App.js

//C:\react-js\myreactdev\src\App.js
import React, { useState, useEffect } from "react";
import "./App.css";

function Search() {
  const [allcountry, setAllcountry] = useState([]);
  const [filterresult, setFilterresult] = useState([]);
  const [serachcountry, setSearchcountry] = useState("");
 
  const handlesearch = (event) => {
    const search = event.target.value;
    console.log(search);
    setSearchcountry(search);
 
    if (search !== "") {
      const filterdata = allcountry.filter((item) => {
        return Object.values(item)
          .join("")
          .toLowerCase()
          .includes(search.toLowerCase());
      });
      setFilterresult(filterdata);
    } else {
      setFilterresult(allcountry);
    }
  };
 
  useEffect(() => {
    const getcountry = async () => {
      const getres = await fetch("http://127.0.0.1:8000/api/autocomplete");
      const setcounty = await getres.json();
      console.log(setcounty.results);
      setAllcountry(await setcounty.results);
    };
    getcountry();
  }, []);
 
  return (
      <div className="container">
        <div className="row"><h3>React JS Laravel 10 AutoComplete Textbox | Filter Search</h3>
          <div className="col-md-6 mb-3 mt-3">
            <input
              type="text"
              className="form-control"
              placeholder="Enter Keyword"
              onChange={(e) => {
                handlesearch(e);
              }}
            />
            <table className="table table-bordered table-striped">
              <thead>
                <tr>
                  <th>Country ID </th>
                  <th>Country Name</th>
                </tr>
              </thead>
              <tbody>
                {serachcountry.length > 1
                  ? filterresult.map((filtercountry, index) => (
                      <tr key={index}>
                        <td> {filtercountry.id} </td>
                        <td> {filtercountry.countryName} </td>
                      </tr>
                    ))
                  : allcountry.map((getcon, index) => (
                      <tr key={index}>
                        <td> {getcon.id} </td>
                        <td> {getcon.countryName} </td>
                      </tr>
                    ))}
              </tbody>
            </table>
          </div>
        </div>
      </div>
  );
}
 
export default Search;
react-js\myreactdev\public\index.html
//react-js\myreactdev\public\index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <title>React App</title>
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"/>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  </body>
</html>
Run C:\react-j\myreactdev>npm start
http://localhost:3000/

Related Post