Laravel 8 Ajax Autocomplete Search from Database Example

Jun 10, 2021 . Admin

Hi Guys,

In This Article, I am going to scratch and learn you how to use and implement ajax autocomplete search from database in laravel 8 application.so We will learn how to utilize in laravel 8 application. I written simple example for ajax autocomplete search. I will justify you ajax autocomplete search in laravel 8.

So, suppose you have thousand or millions records in your database if you are dealing with like you have products table and thousands of records so it's not possible to give drop-down box, but it is better if we use autocomplete instead of select box.

Here i will show you full example of ajax autocomplete search in laravel 8. So let's started first of follow few step to get example.

Step 1 : Install Laravel 8

In the first step, we need to go from scratch , get fresh laravel 8 version application So let's open terminal and run bellow command to install fresh laravel project.

composer create-project --prefer-dist laravel/laravel blog
Step 2 : Database Configuration

In this second step, we will crate database Configuration for example database name, username, password etc for our crud application of laravel 8 So lets open .env file and fill all deatils like as bellow:

Path : .env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=here your database name(blog)
DB_USERNAME=here database username(root)
DB_PASSWORD=here database password(root)
Step 3 : Create Migration Table Path : database/migrations/2021_05_29_064753_create_products_table.php
<?php

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

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

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


After complete configuration and migrate all the tabel so let's open terminal run bellow artisan command:

php artisan migrate
Step 4 : Create Model

Ok, so after run bellow command you will find "app/Product.php" and put bellow content in Product.php file:

<?php

namespace App\Models;

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

class Product extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'price',
        'details',
    ];

}

Step 5: Create Route

Here, we require to integrate route.let's open your "routes/web.php" file and add following route.

Path : routes/web.php
<?php
use App\Http\Controllers\AutosearchController;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

// AutosearchController
Route::get('search', [AutosearchController::class, 'autosearch'])->name('search');
Step 6: Add Controller

In this step, now we should create new controller as AutosearchController. So run bellow command and create new controller.

So, let's copy bellow code and put on AutosearchController.php file.

php artisan make:controller AutosearchController
Path : app/Http/Controllers/AutosearchController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Product;
use Illuminate\Support\Facades\DB;

class AutosearchController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function autosearch(Request $request)
    {
        if ($request->ajax()) {
            $data = Product::where('name','LIKE',$request->name.'%')->get();
            $output = '';

            if (count($data)>0) {
                $output = '
    '; foreach ($data as $row) { $output .= '
  • '.$row->name.'
  • '; } $output .= '
'; }else { $output .= '
  • '.'No Data Found'.'
  • '; } return $output; } return view('autosearch'); } }
    Step 5 : Add Blade File

    In last step. In this step we have to create just blade file. so we need to create only one blade file as autosearch.blade.php file.

    Path : resources/views/autosearch.blade.php
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Laravel 8 Ajax Autocomplete Search from Database Example - MyWebTuts.com</title>
        <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.0-alpha1/css/bootstrap.min.css">
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
    </head>
    <body class="bg-dark">
        <div class="container mt-5">
            <div class="row">
                <div class="col-md-10 offset-1">
                    <div class="card">
                        <div class="card-header">
                            <h5>Laravel 8 Ajax Autocomplete Search from Database Example - MyWebTuts.com</h5>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-12">
                                    <div class="form-group">
                                        <label for="name">Product Name</label>
                                        <input type="text" name="name" id="name" class="form-control" autocomplete="off">
                                    </div>
                                    <div id="product_list"></div>
                                </div>
                                <div class="col-lg-3"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>  
        <script type="text/javascript">
            $(document).ready(function(){
                $('#name').on('keyup',function () {
                    var query = $(this).val();
                    $.ajax({
                        url:'{{ route('search') }}',
                        type:'GET',
                        data:{'name':query},
                        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>
    

    So, Let's get run our laravel 8 application Now we are ready to run our application example with laravel 8 so run bellow command for quick run:

    php artisan serve
    

    Now you can open bellow URL on your browser:

    localhost:8000/search
    

    It will help you...

    #Jquery #Laravel 8 #Laravel