We have already seen some search systems in the Laravel application in my previous tutorial. We have seen using Algolia search, or normal database driver scout search as well as search with normal like query.

In this tutorial, I will show you how to create a real-time live data search example in Laravel using bootstrap typehead js. That means when a user types something in the search bar, then we will show that search data without page refresh using bootstrap typehead js.

We show data from the database using like query operator in laravel with typehead js to complete this manual laravel autocomplete search from database. You know that typehead js is a great library for searching data very quickly from the server. So in this tutorial, we will implement a complete demo laravel 10 search application using typehead js.

You can see the preview in the below image:

laravel-10-typehead-js-search-example

Step 1: Install Laravel

We are going to create a demo search application using typehead js. So we need a fresh Laravel application. 

composer create-project laravel/laravel example-app

 

Step 2: Connect Database

After successfully installing the laravel will open the ".env" file and change the database name, username, and password in the env file to create how to implement search in laravel.

.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=Enter_Your_Database_Name
DB_USERNAME=Enter_Your_Database_Username
DB_PASSWORD=Enter_Your_Database_Password

 

Now update the seeder class like below:

Database\Seeders\DatabaseSeeder.php

<?php

namespace Database\Seeders;

use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use App\Models\User;
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
       for ($i=0; $i < 30; $i++) { 
           $user = new User;
           $user->name = fake()->name();
           $user->email = fake()->email();
           $user->password = bcrypt('secret');
           $user->save();
       }
    }
}

 

Now run the below command to migrate the database.

php artisan migrate

 

Now run the below command to create dummy data:

php artisan db:seed

 

Step 3: Create Route

Now we need to create a route to get user search requests. So create it like this:

routes/web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\TutorialController;

Route::get('/', [TutorialController::class,'index'])->name('index');

 

Step 4: Create Controller

Here, we need to add the index() method for fetching users data with Laravel search query using the like operator in TutorialController. So let's add like as below:

app/Http/Controllers/TutorialController.php

<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Jobs\ProcessCSVData;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Bus;
use Illuminate\Database\Eloquent\Builder;

class TutorialController extends Controller
{
    public function index(Request $request)
    {
        $query = $request->get('query');
        if ($request->ajax()) {
            $result = User::where('name', 'LIKE', '%' . $query . '%')
                ->get();
            return response()->json($result);
        }

        $users = User::where('name', 'LIKE', '%' . $query . '%')
            ->simplePaginate(10);
        return view('welcome', compact('users'));
    }
}

 

Step 5: Create Blade file

In this step, we need to create a welcome blade file and update it like below. so let's change it.

resources/views/welcome.blade.php

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">Laravel 10 Bootstrap Typehead Js Search Example- Laravelia</div>
                 <div class="card-body">
                    <form action="{{ route('index') }}" method="get">
                        <div class="row">
                            <div class="col-md-10">
                                <input type="text" class="form-control mb-3" placeholder="search" name="q" id="searchUser">
                            </div>
                            <div class="col-md-2">
                                <input type="submit" class="form-control mb-3" value="Search">
                            </div>
                        </div>
                    </form>
                    <table style="width: 100%">
                        <thead>
                            <th>#</th>
                            <th>Name</th>
                            <th>Email</th>
                            <th>Status</th>
                        </thead>
                        <tbody>
                            @foreach($users as $user)
                            <tr>
                                <td>{{ $loop->index + 1 }}</td>
                                <td>{{ $user->name }}</td>
                                <td>{{ $user->email }}</td>
                                <td>{{ $user->status == 'active' ? 'Active' : 'Inactive'}}</td>
                            </tr>
                            @endforeach
                        </tbody>
                    </table>
                    <center class="mt-5">
                        {{  $users->withQueryString()->links() }}
                    </center>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection
@push('script')
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.1/bootstrap3-typeahead.min.js">
</script>
<script type="text/javascript">
    var route = "{{ route('index') }}";
    $('#searchUser').typeahead({
        source: function (query, process) {
            return $.get(route, {
                query: query
            }, function (data) {
                return process(data);
            });
        }
    });
</script>
@endpush

 

Now create an app blade file and update it like this: 

resources/views/layouts/app.blade.php

<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ config('app.name', 'Laravel') }}</title>
    
    <!-- Tailwindcss -->
    <script src="https://cdn.tailwindcss.com"></script>

    <!-- Scripts -->
    @vite(['resources/sass/app.scss', 'resources/js/app.js'])
    @stack('style')
</head>
<body>
    <div id="app">
        <nav class="navbar navbar-expand-md navbar-light bg-white shadow-sm">
            <div class="container">
                <a class="navbar-brand" href="{{ url('/') }}">
                    Laravelia
                </a>
                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="{{ __('Toggle navigation') }}">
                    <span class="navbar-toggler-icon"></span>
                </button>

                <div class="collapse navbar-collapse" id="navbarSupportedContent">
                    <!-- Left Side Of Navbar -->
                    <ul class="navbar-nav me-auto">

                    </ul>

                    <!-- Right Side Of Navbar -->
                    <ul class="navbar-nav ms-auto">
                        <!-- Authentication Links -->
                        @guest
                            @if (Route::has('login'))
                                <li class="nav-item">
                                    <a class="nav-link" href="{{ route('login') }}">{{ __('Login') }}</a>
                                </li>
                            @endif

                            @if (Route::has('register'))
                                <li class="nav-item">
                                    <a class="nav-link" href="{{ route('register') }}">{{ __('Register') }}</a>
                                </li>
                            @endif
                        @else
                            <li class="nav-item dropdown">
                                <a id="navbarDropdown" class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-pre>
                                    {{ Auth::user()->name }}
                                </a>

                                <div class="dropdown-menu dropdown-menu-end" aria-labelledby="navbarDropdown">
                                    <a class="dropdown-item" href="{{ route('logout') }}"
                                       onclick="event.preventDefault();
                                                     document.getElementById('logout-form').submit();">
                                        {{ __('Logout') }}
                                    </a>

                                    <form id="logout-form" action="{{ route('logout') }}" method="POST" class="d-none">
                                        @csrf
                                    </form>
                                </div>
                            </li>
                        @endguest
                    </ul>
                </div>
            </div>
        </nav>

        <main class="py-4">
            @yield('content')
        </main>
    </div>
    @stack('script')
</body>
</html>

 

Ok, now we are ready to go and test the typeahead search Laravel tutorial. So let's run the project using this command:

php artisan serve

 

Now you can test our application by visiting the below UR

URL
http://127.0.0.1:8000/

 

Conclusion

Now we know how to typeahead search in Laravel. Hope this manual Laravel autocomplete search from the database tutorial will help you to create bootstrap typeahead in the Laravel application.

Category : #laravel

Tags : #laravel , #laravel search