Skip to content

Laravel 5 Pagination with array

Last updated on November 17, 2022

Laravel provides pagination for Eloquent results out of the box, but for custom data, we need to do the pagination manually.

In this tutorial, I’ll use Laravel5 LengthAwarePaginator class to show you how you can create a paginated list of results from an array of data.

Here is the Script –

Controller – app/Http/Controller/ItemsController.php

<?php

namespace App\Http\Controllers;

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

use App\Http\Requests;

class ItemsController extends Controller
{
     public function items(Request $request)
    {
        $items = [
            'item1',
            'item2',
            'item3',
            'item4',
            'item5',
            'item6',
            'item7',
            'item8',
            'item9',
            'item10'
            ];
 
        // Get current page form url e.x. &page=1
        $currentPage = LengthAwarePaginator::resolveCurrentPage();
 
        // Create a new Laravel collection from the array data
        $itemCollection = collect($items);
 
        // Define how many items we want to be visible in each page
        $perPage = 1;
 
        // Slice the collection to get the items to display in current page
        $currentPageItems = $itemCollection--->slice(($currentPage * $perPage) - $perPage, $perPage)-&gt;all();
 
        // Create our paginator and pass it to the view
        $paginatedItems= new LengthAwarePaginator($currentPageItems , count($itemCollection), $perPage);

        // set url path for generted links
        $paginatedItems-&gt;setPath($request-&gt;url());
 
        return view('items_view', ['items' =&gt; $paginatedItems]);
    }

}

Here is the view file resources/views/item_view.blade.php

<h1>Items List</h1>
<ul>
    @foreach ($items as $item)
        <li>{{ $item }}</li>
    @endforeach
</ul>
<div>{{ $items->links() }}</div>

Define your route as shown below in app/Http/Routes.php

Route::get('items','ItemsController@items');
0 0 votes
Article Rating
Subscribe
Notify of
guest

13 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments