Category : #laravel
Tags : #laravel, #laravel pagination, #laravel ajax
In this tutorial, I will show you how to filter data in laravel using ajax request with pagination and search. I will create a user datatable list. Now I am going to create such a system that a user can move next page without reloading and they can filter the user list according to their status and search users from the table using ajax request.
So from this example, you will learn laravel ajax pagination with filter. I will use laravel users
table to create this laravel ajax filter dropdown. I will put there a search input box for searching users and I will put there a select dropdown box for filter user according to their status.
So let's see the example of filter using ajax in laravel:
Preview of Laravel Ajax Pagination With Search and Filter
Step 1: Install Laravel
First of all, we need to get a fresh Laravel 9 version application using the bellow command, So open your terminal OR command prompt and run the bellow command to start laravel ajax search filter.
composer create-project laravel/laravel example-app
Step 2: Connect Database
After successfully installing the laravel app and then configuring the database setup. We will open the ".env" file and change the database name, username and password in the env file to create filter data in laravel using ajax.
.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
Read also: Ajax Pagination With Search And Filter In Laravel
Step 3: Create Migration and Model
In this step, we need to create users table and model. then we need to run a migration. so let's change the files.
database/migrations/create_users_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->string('status')->nullable()->default(false);
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
};
Now update the user model by replacing it with the below code:
app/Models/User.php
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password'
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
Now you have to run this migration by following the command:
php artisan migrate
Now update the seeder class like below:
Database\Seeders\DatabaseSeeder.php
<?php
namespace Database\Seeders;
use App\Models\Post;
use App\Models\User;
use Illuminate\Support\Str;
use Illuminate\Database\Seeder;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
class DatabaseSeeder extends Seeder
{
public function run()
{
for ($i=0; $i < 100; $i++) {
User::create([
'name' => fake()->name(),
'email' => fake()->unique()->safeEmail(),
'email_verified_at' => now(),
'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi',
'remember_token' => Str::random(10),
'status' => $i % 2 === 0 ? 'active' : 'inactive'
]);
}
}
}
Now run the below command to insert some dummy data.
php artisan db:seed
Read also: Laravel 9 Ajax Pagination With Next Previous Button
Step 4: Create Route
Here, we need to add one more route to display the users data with laravel ajax pagination with filter. so let's add that route in the web.php
file.
routes/web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\TutorialController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', [TutorialController::class,'index'])->name('pagination.fetch');
Step 5: Create Controller
Here, we need to add the index()
method for fetching users data with filter using ajax in laravel in TutorialController. 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)
{
$users = User::query()->paginate(3);
if($request->ajax()){
$users = User::query()
->when($request->seach_term, function($q)use($request){
$q->where('id', 'like', '%'.$request->seach_term.'%')
->orWhere('name', 'like', '%'.$request->seach_term.'%')
->orWhere('email', 'like', '%'.$request->seach_term.'%');
})
->when($request->status, function($q)use($request){
$q->where('status',$request->status);
})
->paginate(3);
return view('pagination_child', compact('users'))->render();
}
return view('welcome',compact('users'));
}
}
Step 6: Create Blade file
In this step, we need to create a welcome blade file and update for user blade file. so let's change it.
resources/views/welcome.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Laravel Search Data with Column Sorting & Pagination using Ajax - Laravelia</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<br />
<div class="container">
<h3 align="center">Laravel Search Data with Filter & Pagination using Ajax - Laravelia</h3><br />
<div class="row">
<div class="col-md-3">
<div class="form-group">
<select name="status" id="status" class="form-control custom-select">
<option value="">Filter</option>
<option value="active">Active</option>
<option value="inactive">InActive</option>
</select>
</div>
</div>
<div class="col-md-6">
</div>
<div class="col-md-3">
<div class="form-group">
<input type="text" name="serach" id="serach" class="form-control" />
</div>
</div>
</div>
<div class="table-responsive">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th width="10%" class="sorting" data-sorting_type="asc" data-column_name="id" style="cursor: pointer">ID <span id="id_icon"></span></th>
<th width="30%" class="sorting" data-sorting_type="asc" data-column_name="name" style="cursor: pointer">Title <span id="post_title_icon"></span></th>
<th width="30%">Description</th>
<th width="30%">Status</th>
</tr>
</thead>
<tbody>
@include('pagination_child')
</tbody>
</table>
<input type="hidden" name="hidden_page" id="hidden_page" value="1" />
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
const fetch_data = (page, status, seach_term) => {
if(status === undefined){
status = "";
}
if(seach_term === undefined){
seach_term = "";
}
$.ajax({
url:"/?page="+page+"&status="+status+"&seach_term="+seach_term,
success:function(data){
$('tbody').html('');
$('tbody').html(data);
}
})
}
$('body').on('keyup', '#serach', function(){
var status = $('#status').val();
var seach_term = $('#serach').val();
var page = $('#hidden_page').val();
fetch_data(page, status, seach_term);
});
$('body').on('change', '#status', function(){
var status = $('#status').val();
var seach_term = $('#serach').val();
var page = $('#hidden_page').val();
fetch_data(page, status, seach_term);
});
$('body').on('click', '.pager a', function(event){
event.preventDefault();
var page = $(this).attr('href').split('page=')[1];
$('#hidden_page').val(page);
var serach = $('#serach').val();
var seach_term = $('#status').val();
fetch_data(page,status, seach_term);
});
});
</script>
Now create a pagination_child blade file and update it like this:
resources/views/pagination_child.blade.php
@foreach($users as $row)
<tr>
<td>{{ $row->id}}</td>
<td>{{ $row->name }}</td>
<td>{{ $row->email }}</td>
</tr>
@endforeach
<tr>
<td colspan="3" align="center">
{!! $users->links('pagination.custom') !!}
</td>
</tr>
Now create a custom pagination blade file and update it like this:
resources/views/pagination/custom.blade.php
@if($paginator->hasPages())
<ul class="pager">
@if ($paginator->onFirstPage())
<li class="disabled"><span>← Previous</span></li>
@else
<li><a href="{{ $paginator->previousPageUrl() }}" rel="prev">← Previous</a></li>
@endif
@foreach ($elements as $element)
@if (is_string($element))
<li class="disabled"><span>{{ $element }}</span></li>
@endif
@if (is_array($element))
@foreach ($element as $page => $url)
@if ($page == $paginator->currentPage())
<li class="active my-active"><span>{{ $page }}</span></li>
@else
<li><a href="{{ $url }}">{{ $page }}</a></li>
@endif
@endforeach
@endif
@endforeach
@if ($paginator->hasMorePages())
<li><a href="{{ $paginator->nextPageUrl() }}" rel="next">Next →</a></li>
@else
<li class="disabled"><span>Next →</span></li>
@endif
</ul>
@endif
Read also: Laravel 9 Ajax Pagination With Next Previous Button
Ok, now we are ready to go and test laravel ajax search with pagination tutorial. So let's run the project using this command:
php artisan serve
Now you can test our application by visiting the below URL:
URL
Conclusion
Now we know laravel ajax pagination with filter. Hope this filter data in laravel using ajax will help you to create laravel ajax filter dropdown.