Make Pagination From Array Or Collection in Laravel

Make Pagination From Array Or Collection in Laravel

Laravel provides pagination for Eloquent , but Sometimes we have to do pagination in Laravel on arrays or collection, we will see how to do Laravel manual pagination.
I’ll use LengthAwarePaginator class
let us start
Controller – app/Http/Controller/HomeController.php

<?php

namespace App\Http\Controllers;

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

use App\Http\Requests;

class HomeController extends Controller
{
     public function index()
    {
        $data = [
            'example 1',
            'example 2',
            'example 3',
            'example 4',
            'example 5',
            'example 6',
            'example 7',
            'example 8',
            'example 9',
            'example 10'
            ];
         $data = $this->paginate($data);

        return view('welcome', ['data' => $data]);
     }

    public function paginate($items, $perPage = 3, )
    {
           // Get current page form url e.x. &page=1
        $page = LengthAwarePaginator::resolveCurrentPage() ?: 1;
          // Get total 
        $total = count($items);
        $currentpage = $page;
           // Slice the collection to get the products to display in current page
        $offset = ($currentpage * $perPage) - $perPage ;
        $itemstoshow = array_slice($items , $offset , $perPage);
          // Create our paginator
        $paginatedItems = new LengthAwarePaginator($itemstoshow ,$total   ,$perPage);
         // Set Url
        $paginatedItems->setPath(request()->url());
        return $paginatedItems;
    }

}

view file
resources/views/welcome.blade.php

<h1>Data List</h1>

<ul>
@foreach ($data as $item) 
   <li> {{ $item }} </li>
@endforeach
</ul>

<div>
{{ $data->links() }}
</div>