Implement Pagination In Laravel Application


What will we Learn?

We will learn how to implement pagination in Laravel Application.

Simple Pagination

Recently,we showed all blog posts in one page. Eventually, if thousands of posts are posted, this will become problematic


Pagination is a good solution to this overload issue. As you may know, creating pagination from scratch is not an easy task

Luckily, Laravel has a paginate method that we can use to create the pagination without having to write any extra code.

Let’s open our BlogController, find:

$posts = Post::all();
Replace with:

$posts = Post::paginate(10);
As you see, we use the paginate method to create the pagination. This will return an instance of IlluminatePaginationLengthAwarePaginator.

I want to display 10 posts on a page, so I put 10 as the parameter. If you would like to use Query Builder, you may write:
$posts = DB::table('posts')->paginate(10);
Next, open the blog/index.blade.php view and find:

@if ($posts->isEmpty())
<p> There is no post.</p>
@else
@foreach ($posts as $post)
<div class="panel panel-default"> 
<div class="panel-heading">
{!! $post->title !!}
</div>
<div class="panel-body"> 
{!! mb_substr($post->content,0,500) !!} 
</div>
</div>
@endforeach 
@endif
Add below:
{!! $posts->render() !!}
Good Job!

Post a Comment

0 Comments