Pagination is one of the best ways for showing a big set of data. Fortunately, The Laravel framework provides the eloquent API for pagination. It's very easy to make pagination. If you already have known about Laravel framework & jQuery and looking an easy way to make Ajax pagination with jQuery in Laravel framework then it's for you. In this tutorial post, I'll show you, how you can make an Ajax pagination with jQuery easily. Here I am using Laravel 6 but the version doesn't a fact for this tutorial. You can easily do exactly the same thing on Laravel 5. Let's follow the simple steps to make an Ajax pagination with jQuery.
Let's make a laravel project by composer command. You can do exactly the same thing if you have already a project.
composer create-project --prefer-dist laravel/laravel laravel-pagination
Put the database details in the project env file and save.
DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=laravel_pagination
DB_USERNAME=root
DB_PASSWORD=
Define two routes in the web.php file. One for returning the pagination data and another for returning view, where we'll make ajax request for pagination.
//routes/web.php
Route::get('posts', 'PostController@index');
Route::get('post-data', 'PostController@postData');
Make the post controller which we have defined in our route definition.
php artisan make:controller PostController
write the code in the post controller.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;
class PostController extends Controller
{
function index()
{
return view('posts.index');
}
function postData(Request $request)
{
if($request->ajax())
{
$data = Post::paginate(10);
return view('posts.data', compact('data'));
}
}
}
?>
We need 2 views inside resources/posts directory. Let's create the first one data.blade.php
<!-- resources/posts/data.blade.php -->
<div class="table-responsive">
<table class="table table-striped table-bordered table-condensed">
<tr>
<th>ID</th>
<th>TITLE</th>
</tr>
@foreach($data as $row)
<tr>
<td>{{ $row->id }}</td>
<td>{{ $row->post_title }}</td>
</tr>
@endforeach
</table>
<div>{!! $data->render() !!}</div>
</div>
Another one index.blade.php
<!-- resources/posts/index.blade.php -->
@extends('layouts.app')
@section('content')
<h2>About</h2>
<div id="posts"></div>
<!-- here jquery script -->
@endsection
Now write jQuery script at the end of the markup in index.blade.php file. Keep in mind, you must have jQuery library include in your template file before using the jQuery script for a pagination.
<script>
(function(){
function getData(page){
if(!page) page=1;
$.get('{{url('/')}}/post-data?page='+page)
.success(function(data){
$('#posts').html(data)
})
}
getData();
$(document).on('click', '.pagination a', function(e){
e.preventDefault();
var page = $(this).attr('href').split('page=')[1];
getData(page);
});
})()
</script>
Now run the server by php artisan serve
command and browser http://localhost:8000/posts