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
PHP 8.3: Release Date and New Features
PHP 8.3: Release Date and New...

Welcome web development enthusiasts! Here, we are going to talk about the much-awaited PHP 8.3. It is packed with a m...

Read More

Jan-12-2023

How to Send E-mail Using Queue in Laravel 7/8
How to Send E-mail Using Queue...

Today I will show you how to send e-mail using queue in laravel 7/8, many times we can see some processes take...

Read More

Oct-30-2020

How To Integrate Swagger In laravel 10
How To Integrate Swagger In la...

In the dynamic realm of modern web development, ensuring that APIs are well-documented, easy to comprehend, and seamless...

Read More

Aug-18-2023

How To Get Multiple Checkbox Value In Javascript
How To Get Multiple Checkbox V...

Checkboxes let us make multiple choices. But how do you actually use them in JavaScript? It might seem tricky, especiall...

Read More

Jan-10-2023