【问题标题】:Slim with laravel pagination, always page 1带有 laravel 分页的 Slim,始终为第 1 页
【发布时间】:2016-06-26 17:19:02
【问题描述】:

我需要 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 或任何其他页面。它始终显示具有相同行的第一页。它说它检测到页码,但显然它是错误的,有没有办法可以手动设置页码,或者如果问题实际上在我的代码中,可以修复?

提前致谢。

【问题讨论】:

    标签: php pagination slim laravel-pagination


    【解决方案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'));
    

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

    【讨论】:

      【解决方案2】:

      问题是 Eloquent 的 Paginator 不知道如何从 Slim 的路由器中提取“page”参数。但是你可以给它一个新的功能来帮助它。这里我创建了一个中间件,告诉 Paginator 如何找到“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()。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-09-01
        • 2016-09-21
        • 1970-01-01
        • 1970-01-01
        • 2018-08-17
        • 2017-10-04
        • 1970-01-01
        相关资源
        最近更新 更多