0

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

3
  • what's the error message? or what does the error prompt? Commented Oct 16, 2019 at 9:46
  • Call to a member function paginate() on array Commented Oct 16, 2019 at 9:47
  • you cant use laravel's paginate on an array, you can only use it on an eloquent model/object Commented Oct 16, 2019 at 9:50

2 Answers 2

2

You can only use paginate on an instance of QueryBuilder or on an Eloquent query.

Instead, if you need to 'paginate' an array, you can use PHP array_chunk.

array_chunk($result, 10, true);
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.