In the previous tutorial, I showed laravel ajax pagination with numeric numbers and laravel ajax pagination with next previous button. In this tutorial, I will show you how to create ajax pagination with search and filter in laravel application.

In this tutorial, simply i will fetch data with ajax request and I will create pagination with them. Then you can filter column wise and then also you can search data from that table with ajax pagination. This tutorial is going to be very interesting if you do not know laravel 9 search filter ajax.

Let's see the example tutorial of how to create pagination with ajax laravel with pagination?

Preview of Laravel Ajax Pagination With Search and Column Filter

laravel-ajax-pagination-with-search-and-filter-example

 

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 ajax pagination with search and filter in laravel.

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 laravel 9 search filter 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: Laravel 9 Ajax Pagination With Numeric Numbers

 

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->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

 

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 search with pagination. 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 how to search using ajax in laravel 9 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()){
            $sort_by = $request->get('sortby');
            $sort_type = $request->get('sorttype');
            $query = $request->get('query');
            $query = str_replace(" ", "%", $query);
            $users = User::query()
                        ->where('id', 'like', '%'.$query.'%')
                        ->orWhere('name', 'like', '%'.$query.'%')
                        ->orWhere('email', 'like', '%'.$query.'%')
                        ->orderBy($sort_by, $sort_type)
                        ->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 Column Sorting & Pagination using Ajax - Laravelia</h3><br />
   <div class="row">
    <div class="col-md-9">
    </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="5%" class="sorting" data-sorting_type="asc" data-column_name="id" style="cursor: pointer">ID <span id="id_icon"></span></th>
       <th width="38%" class="sorting" data-sorting_type="asc" data-column_name="name" style="cursor: pointer">Title <span id="post_title_icon"></span></th>
       <th width="57%">Description</th>
      </tr>
     </thead>
     <tbody>
      @include('pagination_child')
     </tbody>
    </table>
    <input type="hidden" name="hidden_page" id="hidden_page" value="1" />
    <input type="hidden" name="hidden_column_name" id="hidden_column_name" value="id" />
    <input type="hidden" name="hidden_sort_type" id="hidden_sort_type" value="asc" />
   </div>
  </div>
 </body>
</html>

<script>
$(document).ready(function(){
    function clear_icon(){
        $('#id_icon').html('');
        $('#post_title_icon').html('');
    }
    function fetch_data(page, sort_type, sort_by, query){
        $.ajax({
            url:"/?page="+page+"&sortby="+sort_by+"&sorttype="+sort_type+"&query="+query,
            success:function(data){
                $('tbody').html('');
                $('tbody').html(data);
            }
        })
    }
    $('body').on('keyup', '#serach', function(){
        var query = $('#serach').val();
        var column_name = $('#hidden_column_name').val();
        var sort_type = $('#hidden_sort_type').val();
        var page = $('#hidden_page').val();
        fetch_data(page, sort_type, column_name, query);
    });
    $('body').on('click', '.sorting', function(){
        var column_name = $(this).data('column_name');
        var order_type = $(this).data('sorting_type');
        var reverse_order = '';
        if(order_type == 'asc'){
            $(this).data('sorting_type', 'desc');
            reverse_order = 'desc';
            clear_icon();
            $('#'+column_name+'_icon').html('<span class="glyphicon glyphicon-triangle-bottom"></span>');
        }
        if(order_type == 'desc'){
            $(this).data('sorting_type', 'asc');
            reverse_order = 'asc';
            clear_icon
            $('#'+column_name+'_icon').html('<span class="glyphicon glyphicon-triangle-top"></span>');
        }
        $('#hidden_column_name').val(column_name);
        $('#hidden_sort_type').val(reverse_order);
        var page = $('#hidden_page').val();
        var query = $('#serach').val();
        fetch_data(page, reverse_order, column_name, query);
    });
    $('body').on('click', '.pager a', function(event){
        event.preventDefault();
        var page = $(this).attr('href').split('page=')[1];
        $('#hidden_page').val(page);
        var column_name = $('#hidden_column_name').val();
        var sort_type = $('#hidden_sort_type').val();
        var query = $('#serach').val();
        $('li').removeClass('active');
        $(this).parent().addClass('active');
        fetch_data(page, sort_type, column_name, query);
    });
});
</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: Filter Data With Search And Pagination In Laravel Using Ajax

 

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
http://127.0.0.1:8000/

 

Conclusion

Now we know ajax pagination with search and filter in laravel. Hope this laravel 9 search filter ajax will help you to create laravel ajax search with pagination.