带有 laravel 分页的 Slim,总是第 1 页

Slim with laravel pagination, always page 1

我需要 Illuminate/pagination 进入我的 Slim 3 项目

我的路线中有以下内容:

$this->get('/traces', 'UserController:getTraces')->setName('user.traces');

在 getTraces 方法中:

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');
}

在我看来(我正在使用 Twig):

{{ login_rows.render() | raw }}

所以一切正常,还有分页 html 链接,但即使我转到 ?page=2 或任何其他页面。它始终显示具有相同行的第一页 1。它说它检测到页码,但显然它是错误的,如果问题实际上在我的代码中,有没有办法手动设置页码或修复?

提前致谢。

如果有人感兴趣,我就这样做了:

$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'));

这解决了我的问题,我确信有更好的解决方案,但至少它有效!

问题是 Eloquent 的分页器不知道如何从 Slim 的路由器中提取 "page" 参数。但是你可以给它一个新的功能来帮忙。在这里,我创建了一个中间件,告诉分页器如何找到 "page" 参数。

<?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);
    }

}

然后在设置应用程序时,您可以添加:

$app->add(new App\Middleware\Pagination);

请注意,每个页面请求(即使是没有分页的请求)都会 运行。我怀疑这是否真的会影响性能。如果担心,您可以将其应用于特定路线。或者在查询之前调用 currentPageResolver()。