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
Laravel orderBy, groupBy and limit Example
Laravel orderBy, groupBy and l...

In this article, we will see the laravel orderBy, groupBy, and limit examples. Here we will see different types of&...

Read More

Jan-27-2021

How To Validate URL In PHP With Regex
How To Validate URL In PHP Wit...

Hello Guys, In this tutorial we will see how to validate URL in PHP with regex. also you can implement in larave...

Read More

Apr-13-2021

How To Convert Image To Base64 In Laravel 9
How To Convert Image To Base64...

In this article, we will see how to convert an image to base64 in laravel 9. Here, we will convert the image to bas...

Read More

Dec-29-2022

How To Fixed Header In Datatable Using jQuery
How To Fixed Header In Datatab...

Data presentation and organization are easier with data tables. They help display information in an organized way. These...

Read More

Jan-05-2023