Pagination in Laravel
Pagination is a way of splitting up content into several different pages and making content layout far more organized. A must for blogs who wish their front-pages to be small enough to load and yet big enough to showcase the most important tutorials.
Modifying the Controller:
Pagination in Laravel 5 is incredibly easy to implement. In this tutorial I will be using some of the code from this site to serve as an example:
Old Method — No Pagination:
<?php
class ArticleController extends Controller {
public function index()
{
$articles = Article::get();
return view('someview', compact('articles'));
}
}
New Way : With Pagination
<?php
class ArticleController extends Controller {
public function index()
{
$articles = Article::paginate(15);
return view('someview', compact('articles'));
}
}
Modifying the View
So now that we’ve modified the controller we need to then modify the view ever so slightly in order to allow for our pagination. In this example I was printing out key details about my articles in a table and wanted the results to be split up instead of having huge lists of posts to wade through:
@foreach ($articles as $article) {{ $article->id }}
{{ $article->title }}
{{ $article->published }}@endforeach
With the newly added pagination this works fine, but we have no current way to navigate between pages of rows. So in order for us to fix that we add the following wrapped in php tags:
<?php echo $articles->render(); ?>
“Simple Pagination”
If you only need to display simple “Next” and “Previous” links in your pagination view, you may use the simplePaginate
method to perform a more efficient query. This is very useful for large datasets when you do not need to display a link for each page number when rendering your view:
$users = DB::table('users')->simplePaginate(15);
Appending To Pagination Links
You may append to the query string of pagination links using the appends
method. For example, to append sort=votes
to each pagination link, you should make the following call to appends
:
{{ $users->appends(['sort' => 'votes'])->links() }}