phparrayslaravelpagination

can not use pagination() for an array object in laravel


I am constructing an array in Laravel 5.7. I would like to paginate it, but it errors because of array feature. what shall I do?

In 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
 );

Call to a member function paginate() on array


Solution

  • I solved my problems using make() and LengthAwarePaginator as below:

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