Reputation: 47
I required Illuminate/pagination
into my Slim 3 project
I've the following in my route:
$this->get('/traces', 'UserController:getTraces')->setName('user.traces');
In the getTraces method:
public function getTraces($req, $res)
{
$loginRows = $this->db->table('login_history')->where('user_id', $_SESSION['user'])->orderBy('id', 'desc')->paginate(5);
$loginRows->setPath($this->router->pathFor('user.traces'));
$this->view->getEnvironment()->addGlobal('login_rows', $loginRows);
return $this->view->render($res, 'user/traces.twig');
}
In my view (I'm using Twig):
{{ login_rows.render() | raw }}
So everything is working just fine and also the pagination html links, but even if I go to ?page=2
or any other page. It always display first page 1 with same rows. It says that it detect the page number but obviously it's wrong, is there a way I can set the page number manually or a fix if the problem is actually in my code?
Thanks in advance.
Upvotes: 1
Views: 904
Reputation: 265
The problem is that Eloquent's Paginator doesn't know how to extract the "page" parameter from Slim's router. But you can give it a new function to help. Here I've created a middleware that tells the Paginator how to find the "page" parameter.
<?php
/**
* Tells the Eloquent Paginator how to get the current page
*/
namespace App\Middleware;
class Pagination {
public function __invoke($request, $response, $next)
{
\Illuminate\Pagination\Paginator::currentPageResolver(function() use ($request) {
return $request->getParam('page');
});
return $next($request, $response);
}
}
Then when setting up the app, you can add this:
$app->add(new App\Middleware\Pagination);
Be aware that will be run for every page request (even those without pagination). I doubt it's really a performance hit. If concerned, you can apply it to specific routes. Or call currentPageResolver() just before your query.
Upvotes: 0
Reputation: 47
If anyone interested, I just did that:
$loginRows = $this->db->table('login_history')->where('user_id', $_SESSION['user'])->orderBy('id', 'desc')->paginate(5, ['*'], 'page', $req->getParam('page'));
$loginRows->setPath($this->router->pathFor('user.traces'));
This is fixed my problem, I'm sure there is a better solution but at least this works!
Upvotes: 2