Eloquent and Pagination Inside Zend Expressive

Recently working with eloquent (Laravel’s orm), zend expressive and zend view, I wanted to integrate pagination.

It was simple as registering a Paginator middleware.

1
2
3
4
5
6
7
8
9
10
11
use Illuminate\Pagination\Paginator;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

IlluminatePaginator::currentPageResolver(function ($pageName) use ($request) {
    $params = $request->getQueryParams();
    return empty($params[$pageName]) ? 1 : $params[$pageName];
});
IlluminatePaginator::currentPathResolver(function () use ($request) {
    return $request->getUri()->getPath();
});

and you can call paginate on the Model.

Eg : Consider you have a Post model.

1
$posts = Post::paginate(20);

and in view you can iterate through the $posts and render the pagination. The $posts is an object of LengthAwarePaginator.

You can also modify the presenter accordingly. Default comes with BootstrapThreePresenter

1
2
3
4
5
6
7
8
<?php
foreach ($this->posts as $post) {
?>
    <?= $post->title . "<br />" ?>
<?php
}
?>
<?= $this->posts->render() ?>

Note : Please be aware of the issues/10909.

eloquent, expressive, pagination, view, zend

Comments