We can create a live search in Laravel in many ways like using typehead js search or jquery autocomplete search etc. But in this tutorial, we will implement basic search functionalities in laravel 10 application using jQuery ajax.

We will create a live data searching system in Laravel 10 application from scratch. So in this simple jQuery ajax search example in Laravel tutorial, you will learn how to create a simple live search in Laravel. 

To create these search features, I will use user table data. When a user writes something in search input then we will show related data according to the user search. So let's see the example of create laravel search box with live results using ajax jquery:

laravel-10-ajax-live-search-example

Step 1: Install Laravel

We are going to create a demo search application using ajax and jQuery. 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 jquery ajax search in laravel 10.

.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 insert some dummy data.

php artisan migrate

//then

php artisan db:seed

 

Read also: Ajax Pagination With Search And Filter In Laravel

 

Step 3: Create Route

Now we need to create a route to get user ajax 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 like operator in TutorialController with ajax request. so let's add like as below:

app/Http/Controllers/TutorialController.php

<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;

class TutorialController extends Controller
{
    public function index(Request $request)
    {
        $query = $request->get('query');
        if ($request->ajax()) {
            $data = User::where('name', 'LIKE', $query . '%')
                ->limit(10)
                ->get();
            $output = '';
            if (count($data) > 0) {
                $output = '<ul class="list-group">';
                foreach ($data as $row) {
                    $output .= '<li class="list-group-item">' . $row->name . '</li>';
                }
                $output .= '</ul>';
            } else {
                $output .= '<li class="list-group-item">' . 'No results' . '</li>';
            }
            return $output;
        }
        $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 Ajax Autocomplete 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">
                                <span id="userList"></span>
                            </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 type="text/javascript">
    $('#searchUser').on('keyup',function() {
        var query = $(this).val(); 
        $.ajax({
            url:"{{ route('index') }}",
            type:"GET",
            data:{'query':query},
            success:function (data) {
                $('#userList').html(data);
            }
        })
    });
    $('body').on('click', 'li', function(){
        var value = $(this).text();
        //do what ever you want
    });
</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 jquery ajax 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/

 

Read also: Laravel 10 Typehead Js Live Search Tutorial

 

Conclusion

Now we know fetch records from mysql with jquery ajax laravel 10. Hope this create laravel search box with live results using ajax jquery tutorial will help you to create live search in laravel 10 using ajax.

Category : #laravel

Tags : #laravel , #laravel search