Laravel 5 - Manual pagination

You need to add use:

use Illuminate\Pagination\LengthAwarePaginator as Paginator;

and now you can use:

 $paginator = new Paginator($items, $count, $limit, $page, [
            'path'  => $this->request->url(),
            'query' => $this->request->query(),
        ]);

to get data in the same format as paginating on model object;


Example of using the Illuminate\Pagination\LengthAwarePaginator:

use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;

public function getItems(Request $request)
{
    $items = []; // get array/collection data from somewhere
    $paginator = $this->getPaginator($request, $items);

    // now we can treat $paginator as an array/collection
    return view('some-view')->with('items', $paginator);
}

private function getPaginator(Request $request, $items)
{
    $total = count($items); // total count of the set, this is necessary so the paginator will know the total pages to display
    $page = $request->page ?? 1; // get current page from the request, first page is null
    $perPage = 3; // how many items you want to display per page?
    $offset = ($page - 1) * $perPage; // get the offset, how many items need to be "skipped" on this page
    $items = array_slice($items, $offset, $perPage); // the array that we actually pass to the paginator is sliced

    return new LengthAwarePaginator($items, $total, $perPage, $page, [
        'path' => $request->url(),
        'query' => $request->query()
    ]);
}

Then in some-view.blade.php file, for example:

@foreach($items as $item)
    {{--  --}}
@endforeach


{{ $items->links() }}

See https://laravel.com/docs/5.7/pagination#manually-creating-a-paginator