In this tutorial we will learn pagination in Laravel using Ajax jQuery. Laravel provides its own library to build the pagination html, which we can easily use in our html page using $model
->links() method and $model->paginate()
method to make a long list into pagination. But sometimes our requirements are different to use the pagination without refresh the page and show next pagination data. Thus in this tutorial i will show you to use the existing Laravel pagination data with jQuery Ajax.
In this example i will use bootstrap to show better UI with pagination, jQuery to execute Ajax and Laravel pagination to show pagination.
So, let’s begin the tutorial
Step 1: Create a laravel project
First step is to create the Laravel 8 project using composer command or you can also read the How to install laravel 8 ? and Laravel artisan command to generate controllers, Model, Components and Migrations
composer create-project laravel/laravel example-app
Step 2: Configure database
Next step is to configure the database for our project, table and data. So open .env or if file not exist then rename .env.example file to .env
file in root folder and change below details
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=test
DB_USERNAME=root
DB_PASSWORD=
Step 3: Create Model, Migration and Seeders
If you have table and large data already then you can skip this step but if you are beginner and trying to implement pagination then pagination required model, large dataset in table so in this step we are creating a model and migration using artisan command
php artisan make:model Article -m
Above command will create two files one is migration and other one is model. open migration file which is located at database/migrations/timestamp_create_articles_table.php
and edit the schema as below
public function up()
{
Schema::create('articles', function (Blueprint $table) {
$table->id();
$table->string('email')->unique();;
$table->string('title');
$table->string('body');
$table->timestamps();
});
}
Run migration using artisan command in command line
php artisan migrate
Output of above command
Migrating: 2021_11_27_112800_create_articles_table
Migrated: 2021_11_27_112800_create_articles_table (45.63ms)
Now create seeder in database/seeders/DatabaseSeeder.php
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
// Import DB and Faker services
use Illuminate\Support\Facades\DB;
use Faker\Factory as Faker;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* @return void
*/
public function run()
{
$faker = Faker::create();
for ($i=0;$i<=100;$i++) {
DB::table('articles')->insert([
'title' => $faker->name,
'body' => $faker->text,
'email' => $faker->email,
'updated_at' =>$faker->datetime,
'created_at' => $faker->datetime
]);
}
}
}
Run Seeder in command line
php artisan db:seed
Step 4 : Create a controller
Create the controller and add the necessary imports and class. You can create by Laravel artisan or manually.
php artisan make:controller ArticleController
Now, add the controller logic for pagination and ajax
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Article;
class ArticleController extends Controller
{
public function index(Request $request)
{
$articles=Article::when($request->has("title"),function($q)use($request){
return $q->where("title","like","%".$request->get("title")."%");
})->paginate(5);
if($request->ajax()){
return view('articles.article-pagination ',['articles'=>$articles]);
}
return view('articles.article ',['articles'=>$articles]);
}
}
Here, i used Article model to paginate the data and $request->ajax()
method to check if request is Ajax then response with articles.article-pagination
partial page otherwise with full page.
Step 5 : Create the views
Create two views one for full page
and other for list with pagination therefore creating views in resource/articles/article.blade.php and resource/articles/article-pagination.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">
<title>Readerstacks laravel 8 ajax pagination with search </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 href="//netdna.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body class="antialiased">
<div class="container">
<!-- main app container -->
<div class="readersack">
<div class="container">
<div class="row">
<div class="col-md-8 offset-md-2">
<h3>Laravel 8 ajax pagination with search - Readerstacks</h3>
<div id="search">
<form id="searchform" name="searchform">
<div class="form-group">
<label>Search by Title</label>
<input type="text" name="title" value="{{request()->get('title','')}}" class="form-control" />
@csrf
</div>
<div class="form-group">
<label>Search by body</label>
<input type="text" name="body" value="{{request()->get('body','')}}" class="form-control" />
</div>
<a class='btn btn-success' href='{{url("articles")}}' id='search_btn'>Search</a>
</form>
</div>
<div id="pagination_data">
@include("articles.article-pagination",["articles"=>$articles])
</div>
</div>
</div>
</div>
</div>
<!-- credits -->
<div class="text-center">
<p>
<a href="#" target="_top">Laravel 8 ajax pagination with search
</a>
</p>
<p>
<a href="https://readerstacks.com" target="_top">readerstacks.com</a>
</p>
</div>
</div>
<script>
$(function() {
$(document).on("click", "#pagination a,#search_btn", function() {
//get url and make final url for ajax
var url = $(this).attr("href");
var append = url.indexOf("?") == -1 ? "?" : "&";
var finalURL = url + append + $("#searchform").serialize();
//set to current url
window.history.pushState({}, null, finalURL);
$.get(finalURL, function(data) {
$("#pagination_data").html(data);
});
return false;
})
});
</script>
</body>
</html>
As we can see i added bootstrap and jQuery as well. We also include @include("articles.article-pagination",["article"=>$article])
so we can show article on first render.
And resources/views/articles/article-pagination.blade.php
<table class="table table-striped table-dark table-bordered">
<tr>
<th>Sr No.</th>
<th>Title</th>
<th>Body</th>
<th>Date</th>
</tr>
@foreach($articles as $article)
<tr>
<td>{{$article->id}}</td>
<td>{{$article->title}}</td>
<td>{{$article->body}}</td>
<td>{{$article->created_at}}</td>
</tr>
@endforeach
</table>
<div id="pagination">
{{ $articles->links() }}
</div>
Then we have jQuery to handle the pagination and search
$(function() {
$(document).on("click","#pagination a,#search_btn",function(){
//get url and make final url for ajax
var url=$(this).attr("href");
var append=url.indexOf("?")==-1?"?":"&";
var finalURL=url+append+$("#searchform").serialize();
//set to current url
window.history.pushState({},null, finalURL);
$.get(finalURL,function(data){
$("#pagination_data").html(data);
});
return false;
})
});
This is the main part for Ajax pagination here we used jQuery to handle the click on li and search button. then on click we pushed the url and execute the ajax.
Step 6 : Create Routes
Second step is to create the routes to show the form and submit the form
<?php
use Illuminate\Support\Facades\Route;
use \App\Http\Controllers\ArticleController;
Route::get('/articles',[ArticleController::class, 'index']);
Run and final output:
Adding extra params to Laravel pagination
Sometimes we wanted to add extra params to links for example per page parameter to every page then we can use appends
method.
{!! $articles->appends(['per_page' => '20'])->links() !!}
Using bootstrap in Laravel pagination
By default Laravel use Tailwind views
and Laravel also support bootstrap, so to change this behavior we need to call useBootstrap
method within the boot
method of your App\Providers\AppServiceProvider
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Pagination\Paginator;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Paginator::useBootstrap();
}
}