2

I am using pagination in Laravel 5.6 to build an application. I am using Laravel DB instead of Eloquent. However, when I add a pagination link on view, it shows an error Call to a member function links() on array. This is because I am using an array, the default is an object with a collection. The output I am getting looks like

array:12 [▼
    "current_page" => 1
    "data" => array:3 [▶]
    "first_page_url" => "http://127.0.0.1:8000/posts?page=1"
    "from" => 1
    "last_page" => 3
    "last_page_url" => "http://127.0.0.1:8000/posts?page=3"
    "next_page_url" => "http://127.0.0.1:8000/posts?page=2"
    "path" => "http://127.0.0.1:8000/posts"
    "per_page" => 3
    "prev_page_url" => null
    "to" => 3
    "total" => 9
]

When I use normal pagination i.e. without converting to an array, the output is

LengthAwarePaginator {#264 ▼
    #total: 9
    #lastPage: 3
    #items: Collection {#251 ▶}
    #perPage: 3
    #currentPage: 1
    #path: "http://127.0.0.1:8000/posts"
    #query: []
    #fragment: null
    #pageName: "page"
}

The problem I face here is adding other data to collection

I can't use the default output return by pagination() method. Can someone please suggest how to solve this issue?

6
  • Please post your view code and any controller code that might be relevant as well. Jul 13, 2018 at 0:11
  • I didn't get you. Could you please explain it again?
    – Ashish
    Jul 13, 2018 at 0:12
  • Please show us the code which creates the pagination object (usually it is in a controller class) and the code which adds the pagination link to the HTML code (usually it is in a view template).
    – Finesse
    Jul 13, 2018 at 0:30
  • Inside view I used $page->links() to show the pagination. Used toArray() to convert collection of object to an array
    – Ashish
    Jul 13, 2018 at 0:35
  • adding what other data to collection?
    – lagbox
    Jul 13, 2018 at 2:08

1 Answer 1

0

Using the below, I am getting the required output.

Step 1: Include LengthAwarePaginator in the file

use Illuminate\Pagination\LengthAwarePaginator;

Step 2: Create an object of LengthAwarePaginator

$paginate = new LengthAwarePaginator(Array, countOfArray, perPage, currentPage, [
        'path' =>  request()->url(),
        'query' => request()->query()
]);

I kept currentPage value as null.
Return $paginate to view.

return view('home', ['data' => Array, 'page' => $paginate]);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.