Laravel 8 Autocomplete Search From Database

Laravel autocomplete textbox search from database using jQuery ui and ajax. In this post, i will show you how to build autocomplete textbox search from database in laravel 8 using jQuery ui and ajax.

In this example post, i will use jQuery ui and ajax for build autocomplete search textbox in laravel 8 app.

So, in this post/article will step by step show you on how to build ajax and jQuery autocomplete search from database in laravel 8 application.

This laravel 8 autocomplete search textbox with jQuery ui and ajax will look like in following image:

jQuery UI Autocomplete Search Textbox in Laravel with Ajax

  • Step 1 – Install Laravel 8 Application
  • Step 2 – Database Configuration
  • Step 3 – Add Dummy Record Into Database For Autocomplete Search
  • Step 4 – Create Routes
  • Step 5 – Creating Autocomplete Search Controller
    • Create method to display autocomplete search form
    • Create method to search from database
  • Step 6 – Create Blade File For Autocomplete Search Form
  • Step 7 – Start Development Server
  • Step 8 – Run Laravel 8 Autocomplete Textbox Search From Database On Browser

Step 1 – Install Laravel 8 Application

In step 1, open your terminal and navigate to your local web server directory using the following command:

//for windows user
cd xampp/htdocs

//for ubuntu user
cd var/www/html

Then install laravel 8 latest application using the following command:

composer create-project --prefer-dist laravel/laravel demo

Step 2 – Database Configuration

In step 2, open your downloaded laravel 8 app into any text editor. Then find .env file and configure database detail like following:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db name
DB_USERNAME=db user name
DB_PASSWORD=db password

Step 3 – Add Dummy Record Into Database For Autocomplete Search

In step 3, Generate dummy records into database table users. So, navigate database/seeders/ directory and open DatabaseSeeder.php file. Then add the following two line of code it:

use App\Models\User;

User::factory(100)->create();

After that, open command prompt and navigate to your project by using the following command:

cd / demo

Now, open again your terminal and type the following command on cmd to create tables into your selected database:

php artisan migrate

Next, run the following database seeder command to generate dummy data into database:

php artisan db:seed

Step 4 – Create Routes

In step 4, open your web.php file, which is located inside routes directory. Then add the following routes into web.php file:

Route::get('autocomplete', [AutocompleteSearchDBController::class, 'index']);
Route::get('search-from-db', [AutocompleteSearchDBController::class, 'searchDB']);

Step 5 – Creating Autocomplete Search Controller

In step 5, create autocomplete textbox search controller by using the following command:

php artisan make:controller AutocompleteSearchDBController

The above command will create AutocompleteSearchDBController.php file, which is located inside LaravelAutocomplete/app/Http/Controllers/ directory.

Then create two methods inside this controller file:

  • Create method to display autocomplete search form
    public function index()
    {
        return view('autocomplete-textbox-search');
    }
  • Create method to search from database
    public function searchDB(Request $request)
    {
          $search = $request->get('term');
      
          $result = User::where('name', 'LIKE', '%'. $search. '%')->get();
 
          return response()->json($result);
            
    }

The full source code of autocomplete search controller following:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\User;

class AutocompleteSearchDBController extends Controller
{
    public function index()
    {
        return view('autocomplete-textbox-search');
    }
 
    public function searchDB(Request $request)
    {
          $search = $request->get('term');
      
          $result = User::where('name', 'LIKE', '%'. $search. '%')->get();
 
          return response()->json($result);
            
    } 
}

Step 6 – Create Blade File For Autocomplete Search Form

In step 6, create new blade view file that named autocomplete-textbox-search.blade.php inside resources/views directory for ajax get data from database.

And the following jQuery and ajax code will autocomplete search data from database in laravel:

<script>
 $(document).ready(function() {
    $( "#name" ).autocomplete({
 
        source: function(request, response) {
            $.ajax({
            url: "{{url('search-from-db')}}",
            data: {
                    term : request.term
             },
            dataType: "json",
            success: function(data){
               var resp = $.map(data,function(obj){
                    return obj.name;
               }); 
 
               response(resp);
            }
        });
    },
    minLength: 2
 });
});
 
</script> 

And the following jQuery ui library will help to design textbox and customize ajax search code:

  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.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>

Don’t worry i have already added the jQuery ajax code and library to get data from database in laravel on blade views.

So, you can add the following php and html form code into autocomplete-textbox-search.blade.php:

<!DOCTYPE html>
<html>
<head>
	<title>Laravel 8 Autocomplete Textbox From Database with jQuery UI</title>
	<meta name="csrf-token" content="{{ csrf_token() }}">

	<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.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>

</head>
<body>

<div class="container mt-4">

  <div class="card">
    <div class="card-header text-center font-weight-bold">
      <h2>Laravel 8 Autocomplete Textbox From Database</h2>
    </div>
    <div class="card-body">
      <form name="autocomplete-textbox" id="autocomplete-textbox" method="post" action="#">
       @csrf

        <div class="form-group">
          <label for="exampleInputEmail1">Search By Name</label>
          <input type="text" id="name" name="name" class="form-control">
        </div>

      </form>
    </div>
  </div>
  
</div>	
</body>
<script>
 $(document).ready(function() {
    $( "#name" ).autocomplete({
 
        source: function(request, response) {
            $.ajax({
            url: "{{url('search-from-db')}}",
            data: {
                    term : request.term
             },
            dataType: "json",
            success: function(data){
               var resp = $.map(data,function(obj){
                    return obj.name;
               }); 
 
               response(resp);
            }
        });
    },
    minLength: 2
 });
});
 
</script>   

</html>

Step 7 – Start Development Server

Finally, open your command prompt again and run the following command to start development server:

php artisan serve

Step 8 – Run Laravel 8 Autocomplete Textbox Search From Database On Browser

In step 8, open your browser and fire the following url into your browser:

http://127.0.0.1:8000/autocomplete-textbox

When you fire the above given url on browser. So, you will look like laravel 8 autocomplete search textbox with jQuery ui and ajax:

laravel-8-autocomplete-textbox-from-database
laravel-8-autocomplete-textbox-from-database

Recommended Laravel Tutorials

Leave a Comment