Laravel 8 Autocomplete Search From Database Tutorial

Laravel

61

Sumit Suryavanshi

12-11-2020


Laravel 8 ajax autocomplete search from db. In this example, i will explain you how to create autocomplete search from database using jQuery UI and ajax in laravel 8 app.

If you are finding such as laravel autocomplete search text box, jquery ui autocomplete example, laravel autocomplete search with jqueryui, laravel dropdown autocomplete, ajax autocomplete text, ajax autocomplete search in laravel, search operation in laravel, etc,

So, in this tutorial, you will learn step by step how to implement autocomplete textbox search app in laravel 8 app using jQuery UI and ajax from mysql database. And as well as learn how to fetch data from the database without refresh or reloading the whole web page.

Laravel 8 Autocomplete Search From DB Example

  • Install Laravel Application
  • Configure Database Detail
  • Run Migration
  • Create Fake Data in Table
  • Create Routes
  • Generate Controller By Artisan
  • Create Blade View
  • Start Development Server

Install Laravel Application

First Step, you need to download or install laravel web application new setup on your local machine. you can use the following command to download or install laravel application new setup:

composer create-project laravel/laravel laravel-autocomplete-search –-prefer-dist

If you want to install a specific version of laravel, you can follow the following tutorial

https://w3alert.com/laravel-tutorial/laravel-install-on-windows-ubuntu-with-composer

Configure Database Detail

After that, you will set up the database credentials in .env file. So open your .env file and update database credentials following:

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

Run Migration

Next, go to command prompt and run the following command:

php artisan migrate

OR

php artisan migrate:fresh

This php artisan migrate command creates a table in your database.

Generate Fake data in Table

Next, we need to generate fake data into the MySQL database table by using php artisan command. So go to your command prompt (cli) and then go to your project root directory. After that run the following command:

php artisan tinker

After run the php artisan tinker. Use the following command. This command will add 200 fake data in your MySQL database table users:

>>> factory(App\User::class, 200)->create();

Create Routes

Next step, go to routes/web.php file and update the following routes into your file:

use App\Http\Controllers\AutoCompleteSearchController;


Route::get('query', [AutoCompleteSearchController::class, 'index']);
Route::get('autocomplete', [AutoCompleteSearchController::class, 'autocomplete']);

Create Controller By Artisan

Now, you need to generate or create a controller file using php artisan command, so use the php artisan make:controller command and generate/create a new controller file:

php artisan make:controller AutoCompleteSearchController

We will create two methods in this controller file. This method will also show the search form and complete search from the database in laravel web applications.

After that, go to App/Http/Controllers/ directory and find the created AutoCompleteSearchController file and update the following code into your file:

<?php

namespace App\Http\Controllers;

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

class AutoCompleteSearchController extends Controller
{

    public function index()
    {
        return view('search-page');
    }

    public function autocomplete(Request $request)
    {
          $search = $request->get('term');
     
          $result = User::where('name', 'LIKE', '%'. $search. '%')->get();

          return response()->json($result);
           
    } 
}

Create Blade Views

Next, you need to create a blade views file, so go resource/views directory and create the following blade views file.

You need to include the following css and JavaScript library in the form below.

  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

Go to resource/views/ then create a new file name search-page.blade.php and update the following code:

<!DOCTYPE html>
<html>
<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() }}">
  <title>Laravel 8 AutoComplete Search Using Jquery UI - W3alert.com.com</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
 <style>
    .container{
    padding: 10%;
    text-align: center;
   } 
 </style>
</head>
<body>

<div class="container">
    <div class="row">
        <div class="col-12"><h2>Laravel 8 AutoComplete Search Using Jquery UI</h2></div>
        <div class="col-12">
            <div id="custom-search-input">
                <div class="input-group">
                    <input id="search" name="search" type="text" class="form-control" placeholder="Search" />
                </div>
            </div>
        </div>
    </div>
</div>
<script>
 $(document).ready(function() {
    $( "#search" ).autocomplete({

        source: function(request, response) {
            $.ajax({
            url: "{{url('autocomplete')}}",
            data: {
                    term : request.term
             },
            dataType: "json",
            success: function(data){
               var resp = $.map(data,function(obj){
                    //console.log(obj.city_name);
                    return obj.name;
               }); 

               response(resp);
            }
        });
    },
    minLength: 1
 });
});

</script>   
</body>
</html>

Start development server

You can use the following command artisan command to start the development server:

php artisan serve

The final step, go to your browser and type the below-given URL into your browser:

http://localhost:8000/query

OR

http://localhost/laravel-autocomplete-search/public/query