Autocomplete Search from Database in Laravel 11

Websolutionstuff | Jun-24-2024 | Categories : Laravel MySQL

Hello, laravel web developers! In this article, we'll see how to autocomplete a search from a database in laravel 11. Here, we'll use typehead js to search records from the MySQL database in laravel 11. Typehead.js is a fast and fully-featured autocomplete library.

We'll create simple and easy autocomplete search records from the database in laravel 11. So, we'll create a model and migration controller.

Laravel 11 Autocomplete Search from Database

autocomplete_search_from_database_laravel_11

 

Step 1: Install Laravel 11 Application

In this step, we'll install 11 applications using the following command.

composer create-project laravel/laravel example-app

 

Step 2: Create Dummy Users

Next, we'll create dummy users using the tinker.

php artisan tinker
    
User::factory()->count(50)->create()

 

Step 3: Create Controller

Then we'll create a controller and add the function for view autocomplete search and the other is for Ajax call to search records into the database.

app/Http/Controllers/SearchController.php

<?php
   
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\View\View;
use Illuminate\Http\JsonResponse;
  
class SearchController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(): View
    {
        return view('search');
    }
        
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function autocomplete(Request $request): JsonResponse
    {
        $data = User::select("name")
                    ->where('name', 'LIKE', '%'. $request->get('query'). '%')
                    ->take(10)
                    ->get();
       
        return response()->json($data);
    }
}

 

Step 4: Define Routes

Now, define the routes into the web.php file.

routes/web.php

<?php
    
use Illuminate\Support\Facades\Route;
   
use App\Http\Controllers\SearchController;
    
Route::get('search', [SearchController::class, 'index']);
Route::get('autocomplete', [SearchController::class, 'autocomplete'])->name('autocomplete');

 

Step 5: Create View File

 

resources/views/search.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Autocomplete Search from Database in Laravel 11 - Websolutionstuff</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.1/bootstrap3-typeahead.min.js"></script>
</head>
<body>
       
<div class="container">
    <div class="card mt-5">
        <h3 class="card-header p-3">Autocomplete Search from Database in Laravel 11 - Websolutionstuff</h3>
        <div class="card-body">
            
            <form action="#" method="POST" enctype="multipart/form-data" class="mt-2">
                @csrf
       
                <input class="typeahead form-control" id="search" type="text">
        
                <div class="mb-3 mt-3">
                    <button type="submit" class="btn btn-success">Submit</button>
                </div>
             
            </form>
        </div>
    </div>  
      
</div>
      
<script type="text/javascript">
      
    var path = "{{ route('autocomplete') }}";
    
    $('#search').typeahead({
        source: function (query, process) {
            return $.get(path, {
                query: query
            }, function (data) {
                return process(data);
            });
        }
    });
    
</script>
      
</body>
</html>

 

Step 6: Run the Laravel 11 Application

Now, run the laravel 11 application using the following command.

php artisan serve

 


You might also like:

Recommended Post
Featured Post
How To Validate Username And Password In React JS
How To Validate Username And P...

In this article, we will see how to validate username and password in react js. In this example, we will validate t...

Read More

Sep-13-2022

How To Generate PDF File In Laravel 10
How To Generate PDF File In La...

In this article, we will see how to generate a pdf file in laravel 10. Here, we will learn about laravel 10 ge...

Read More

Mar-10-2023

Laravel 8 Toastr Notifications Example
Laravel 8 Toastr Notifications...

Today, I will show you Laravel 8 Toastr Notifications Example. There are many types of notifications availa...

Read More

Oct-19-2020

How To Create Custom Command In Laravel 9
How To Create Custom Command I...

In this article, we will see how to create a custom command in laravel 9. Here we will learn about how to make cust...

Read More

Feb-14-2023