I am trying to create a paginated resultset in Lumen. I am not using a database collection, instead it is an array collection.
I have managed to get the results to display, however I am having a problem getting the pagination links() method to work. Here is what I have:
PHP:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
class AppController extends Controller
{
public function index(Request $request)
{
$items = [
'item1',
'item2',
'item3',
'item4',
];
$collection = collect($items);
$currentPage = LengthAwarePaginator::resolveCurrentPage();
$perPage = 2;
$offset = ($currentPage * $perPage) - $perPage;
$currentPageResults = $collection->slice($offset, $perPage)->all();
$paginatedItems = new LengthAwarePaginator($currentPageResults, count($collection), $perPage);
$paginatedItems->setPath($request->url());
return view('index', [
'results' => $paginatedItems,
]);
}
}
View:
<ul>
@foreach ($results as $result)
<li>{{ $result }}</li>
@endforeach
</ul>
<div>
{{ $results->links() }}
</div>
The error I am getting is:
call_user_func() expects parameter 1 to be a valid callback, no array or string given
If I remove $results->links()
I don't get the error.
When I dd($paginationItems)
I do get back a valid LengthAwarePaginator
object:
I found the answer:
Within bootstrap/app.php
there is a line of code commented out by default:
// $app->withEloquent();
This needs to be uncommented for the pagination links() method to work.