Live search in laravel 8 using ajax and Mysql

Cahyo Fajar Pamungkas
3 min readOct 8, 2021

--

Demo Laravel Live Search using AJAX

Hello buddy, welcome back with me in this tutorial we will learn together about Live search in laravel using ajax step by step, with live search using ajax you can search data in real-time such as e-commerce like Tokopedia amazon, etc, in this tutorial we will learn to use ajax to search data in real-time without any page refresh.

Step :

  • Install project laravel
  • set DB_DATABASE=yourdatabase in .ENV
  • create model migration and controller Employee
  • create factory dummy data
  • create your magic code

Install project laravel

composer create-project — prefer-dist laravel/laravel project_name

create database and change file .ENV like below :

DB_CONNECTION=mysqlDB_HOST=127.0.0.1DB_PORT=3306DB_DATABASE=yourdatabaseDB_USERNAME=rootDB_PASSWORD=

Create model migration and controller Employee

php artisan make:model Employee -mc

open file migration in database/migrations/2021_10_08_084636_create_employees_table.php

change with this :

public function up(){  Schema::create('employees', function (Blueprint $table) {    $table->id();    $table->string('name');    $table->string('phone');    $table->timestamps();  });}

and then :

php artisan migrate

open Model: app/models/Employee.php

add this :

<?phpnamespace App\Models;use Illuminate\Database\Eloquent\Factories\HasFactory;use Illuminate\Database\Eloquent\Model;
class Employee extends Model{ use HasFactory; protected $guarded = [];}

after we make table migration and we can create a faker data dummy of laravel faker, let’s started :

php artisan make:factory EmployeeFactory --model=Employee

open file factory : database/factories/EmployeeFactory.php

change with this :

public function definition(){  return [    'name' => $this->faker->name(),    'phone' => $this->faker->phoneNumber()   ];}

after that open the command :

php artisan tinker// and then copy this codeApp\Models\Employee::factory()->count(20)->create()

Yeah, we just made faker data with the factories of laravel

After that change route web.php

namespace App\Http\Controllers; // add namespaceRoute::get('/employee',[EmployeeController::class,'index']);Route::post('/employee/search',[EmployeeController::class,'showEmployee'])->name('employee.search');

open the EmployeeController.php and change with this :

<?phpnamespace App\Http\Controllers;use App\Models\Employee;use Illuminate\Http\Request;class EmployeeController extends Controller{   public function index()   {      return view('Employee.index');   }   public function showEmployee(Request $request)   {      $employees = Employee::all();      if($request->keyword != ''){      $employees = Employee::where('name','LIKE','%'.$request-       >keyword.'%')->get();      }      return response()->json([         'employees' => $employees      ]);    }}

After that create a view in: resources/views/Emoloyee/index.blade.php

Open file index.blade.php and change with this :

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><meta name="csrf-token" content="{{ csrf_token() }}" /><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"><title>Employee Live Search with AJAX</title></head><body>   <div class="container">     <h4 class="text-center mt-4">Live Search in Laravel 8 using      AJAX MySql</h3>      <div class="row mt-5">         <div class="col-md-12">           <div class="card">                <div class="card-body">                   <form action="" method="POST">                       <div class="row">                         <div class="col-md-6">                            <div class="input-group mb-3">             <input type="text" class="form-control"   placeholder="Search employee" id="search">                <div class="input-group-prepend">                 <span class="input-group-text" id="basic-addon1"> <img src="https://assets.tokopedia.net/assets-tokopedia-  lite/v2/zeus/kratos/af2f34c3.svg" alt=""></span></div></div></div></div></form><table class="table table-striped table-inverse table-responsive d-table"><thead><tr><th>No</th><th>Name</th><th>Phone Number</th></tr></thead><tbody></tbody></table></div></div></div></div></div><script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>{{-- <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> --}}<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script><script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script></body></html>

add javascript file inside tag <script>

copy this js code :

<script>$('#search').on('keyup', function(){    search();});search();
function search(){ var keyword = $('#search').val(); $.post('{{ route("employee.search") }}', { _token: $('meta[name="csrf-token"]').attr('content'), keyword:keyword }, function(data){ table_post_row(data); console.log(data); });}// table row with ajaxfunction table_post_row(res){let htmlView = '';if(res.employees.length <= 0){ htmlView+= ` <tr> <td colspan="4">No data.</td> </tr>`;}for(let i = 0; i < res.employees.length; i++){ htmlView += ` <tr> <td>`+ (i+1) +`</td> <td>`+res.employees[i].name+`</td> <td>`+res.employees[i].phone+`</td> </tr>`;} $('tbody').html(htmlView);}</script>
Demo Laravel Live Search using AJAX

Taraaa we just made this live search with laravel using ajax, Thank you very much for reading this tutorial, hopefully those who read it will be given health by God, hopefully this tutorial will be useful for many people :)

see you next tutorial.

--

--

Cahyo Fajar Pamungkas

I'm Fullstack web developer and I’m still learning, I interested with new teck stack