【问题标题】:can not use pagination() for an array object in laravellaravel 中的数组对象不能使用 pagination()
【发布时间】:2020-02-13 01:29:21
【问题描述】:

我正在 Laravel 5.7 中构建一个数组。我想对其进行分页,但由于数组功能而出错。我该怎么办?

在 MyController.php 中:

$result = array();
foreach ($sameDateMatches as $key => $date) {
   array_push($result, [
   'date' => $key,
   'day_of_week' => getDayOfWeek($key),
   'matches' => $date,
    ]);
 }

 if (!empty($_GET['page'])) {
    $result = $result->paginate(10);
    $pagination = $result;
 } else {
    $result = $result;
    $pagination = null;
 }

return returnSuccessfulResponse(
   trans('api.response.successful.show'),
      [
        'Scheduled Matches' => $result,
      ],
      $pagination
 );

调用数组上的成员函数 paginate()

【问题讨论】:

  • 错误信息是什么?或者错误提示什么?
  • Call to a member function paginate() on array
  • 你不能在数组上使用laravel的分页,你只能在雄辩的模型/对象上使用它

标签: arrays laravel pagination


【解决方案1】:

您只能在QueryBuilder or on an Eloquent query 的实例上使用paginate

相反,如果您需要对数组进行“分页”,您可以使用PHP array_chunk

array_chunk($result, 10, true);

【讨论】:

    【解决方案2】:

    我使用make()LengthAwarePaginator 解决了我的问题,如下所示:

    if (!empty($_GET['page'])) {
    
         $per_page = !empty($_GET['per_page']) ? $_GET['per_page'] : 10;
    
         $page = $_GET['page'];
    
         $result = $result instanceof Collection ? $result : Collection::make($result);
    
         $result = new LengthAwarePaginator(
                        $result->forPage($page, $per_page)->values(),
                        $result->count(),
                        $per_page,
                        $page,
                        ['path' => request()->url()]
                  );
    
         $pagination = $result;
    
    } else {
         $pagination = null;
    }
    

    【讨论】:

      猜你喜欢
      • 2019-11-14
      • 1970-01-01
      • 2019-12-07
      • 1970-01-01
      • 2020-02-07
      • 2019-12-11
      • 1970-01-01
      • 2018-04-12
      • 1970-01-01
      相关资源
      最近更新 更多