In this article, I am going to write about laravel 10 ajax live search,
Through this complete guide about laravel 10 ajax live search, you will learn how to handle users’ input search term and pass it to the controller via ajax and loop our records in the controller and pass the HTML code to the view.
We will work with the user’s table for this project, firstly we list all our database users, and then will search through users.
Let’s get through the steps on how to do laravel 10 ajax live search.
Step 1: Install Laravel
We will install a fresh laravel 10 project using the below command.
composer create-project laravel/laravel ajaxSearch --prefer-dist
The above command will create a laravel 10 fresh project on the path we determined.
Step 2: Set database configuration up
In this step, we will create a connection to the database with the .env file, which is located in the root directory of our laravel 10 project.
Before database configuration, create a database you want to work with.
Then open the .env file, and paste the following codes in it.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=ajaxsearch
DB_USERNAME=root
DB_PASSWORD=
Step 3: Fill the users table with some dummy data
If your users table does not have enough data to search through, use the below command to generate some dummy records database.
php artisan thinker
The above command will open Artisan Console, then run the below command into the thinker console.
User::factory()->count(20)->create()
This command will generate 20 random and dummy records.
Step 4: Create UsersController
After the database setup and generating dummy data, we need to create a controller in our laravel 10 porject.
With the help of the below command, we will create a fresh controller.
php artisan make:controller UsersController
The above command will create UserController in our laravel 10 project into the “app/Http/Controllers” directory of our laravel 10 project. Open UsersController.php file and paste the following codes into that file.
UsersController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use DB;
class UsersController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$users = User::latest()->get();
return view('users', compact('users'));
}
function action(Request $request)
{
if ($request->ajax()) {
$output = '';
$query = $request->get('query');
if ($query != '') {
$data = DB::table('users')
->where('name', 'like', '%' . $query . '%')
->orWhere('email', 'like', '%' . $query . '%')
->get();
} else {
$data = DB::table('users')
->orderBy('id', 'desc')
->get();
}
$total_row = $data->count();
if ($total_row > 0) {
foreach ($data as $row) {
$output .= '
<tr>
<td>' . $row->id . '</td>
<td>' . $row->name . '</td>
<td>' . $row->email . '</td>
<td>' . $row->created_at . '</td>
</tr>
';
}
} else {
$output = '
<tr>
<td align="center" colspan="5">Nothing to show, please recheck your search term.</td>
</tr>
';
}
$data = array(
'table_data' => $output
);
echo json_encode($data);
}
}
}
Step 5: Create View files
For this laravel 10 ajax live search project, we need at least one blade view file to list our users and place our search input. For that go to “resources/views” directory and create a blade file by the name of users.blade.php, and paste the bellow scripts into it.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Ajax Search in Laravel 10</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" crossorigin="anonymous"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<div class="container table-responsive py-5">
<div class="row">
<div class="col-12">
<h2>Laravel 10 Ajax Search </h2>
</div>
<div class="col-12">
<form action="">
<label for="q">Search Users</label>
<input type="text" name="search" id="search" class="form-control" placeholder="Search Users..." />
</form>
</div>
</div>
<br>
<table class="table table-bordered table-hover" id="users_list">
<thead class="thead-dark">
<tr>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">Email</th>
<th scope="col">Created At</th>
</tr>
</thead>
<tbody>
@foreach($users as $user)
<tr>
<th scope="row">{{$user->id}}</th>
<td>{{$user->name}}</td>
<td>{{$user->email}}</td>
<td>{{$user->created_at}}</td>
</tr>
@endforeach
</tbody>
</table>
</div>
<script>
$(document).ready(function() {
$(document).on('keyup', '#search', function() {
var query = $(this).val();
fetch_customer_data(query);
function fetch_customer_data(query = '') {
$.ajax({
url: "{{ route('ajax_search.action') }}",
method: 'GET',
data: {
query: query
},
dataType: 'json',
success: function(data) {
$('tbody').html(data.table_data);
}
})
}
});
});
</script>
</body>
</html>
Step 6: Create Routes
To address our users list and send the user’s query term to the controller, we need to create two routes. For that purpose, go to “routes” directory and open web.php file and write the below codes into it.
<?php
use App\Http\Controllers\UsersController;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::get('users-list', [UsersController::class, 'index'])->name('users-list');
Route::get('/ajax_search/action', [UsersController::class, 'action'])->name('ajax_search.action');
Step 7: Final Step
Congratulations, you are done with laravel 10 ajax live search.
Now, run your laravel 10 project using below command.
php artisan serve
And visit the below URL to see the result.
http://localhost:8000/users-list
One thought on “Laravel 10 Ajax Live Search”