Laravel has make pagination very easy. In this post I will show you how to make a single Ajax pagination in Laravel with jQuery.
Controller: app/controllers/BlogController.php
<?php
class BlogController extends Controller
{
/**
* Posts
*
* @return void
*/
public function showPosts()
{
$posts = Post::paginate(5);
if (Request::ajax()) {
return Response::json(View::make('ajax-posts')->with(compact('posts'))->render());
}
return View::make('blog')->with(compact('posts'));
}
// ...
}
View: blog.blade.php
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Laravel Ajax Pagination with jQuery</title>
</head>
<body>
<div id="post-ajax">
@foreach ($posts as $post)
<article>
<h2>{{ $post->title }}</h2>
{{ $post->summary }}
</article>
@endforeach
{{ pagination($posts->appends(Input::except('page')), 'layout.paginator') }}
<div>
<script src="//code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
// Ajax pagination
$(function() {
$('#post-ajax').on('click', '.pagination a', function (e) {
getPosts($(this).attr('href').split('page=')[1]);
e.preventDefault();
});
});
function getPosts(page) {
$.ajax({
url : '?page=' + page,
dataType: 'json',
}).done(function (data) {
$('#post-ajax').html(data);
}).fail(function () {
alert('Posts could not be loaded.');
});
}
</script>
</body>
</html>
View: ajax-posts.blade.php
<div id="post-ajax">
@foreach ($posts as $post)
<article>
<h2>{{ $post->title }}</h2>
{{ $post->summary }}
</article>
@endforeach
{{ pagination($posts->appends(Input::except('page')), 'layout.paginator') }}
<div>
Related Article
Outstanding........................
THX!
Now, how do we change the active url?
When I click the 2nd page, the data loaded but the active page is still first page. What is solution for this?