Laravel Pagination with Array or Object

Satyam.Conaxweb
1 min readJun 24, 2021

--

You have used Laravel Pagination with Eloquent results. Sometimes we have to do paginations in Laravel on arrays or custom objects. In this tutorial, we will see how to do Laravel manual pagination.

Here we are going to use LengthAwarePaginator class of Laravel to create custom pagination in Laravel.

Here is the code to implement custom Pagination in Laravel.

//In Controller

<?php

namespace App\Http\Controllers;

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

use App\Http\Requests;

class productsController extends Controller
{
public function products(Request $request)
{
$products = [
'product1',
'product2',
'product3',
'product4',
'product5',
'product6',
'product7',
'product8',
'product9',
'product10'
];

// Get current page form url e.x. &page=1
$currentPage = LengthAwarePaginator::resolveCurrentPage();

// Create a new Laravel collection from the array data
$productCollection = collect($products);

// Define how many products we want to be visible in each page
$perPage = 1;

// Slice the collection to get the products to display in current page
$currentPageproducts = $productCollection->slice(($currentPage * $perPage) - $perPage, $perPage)->all();

// Create our paginator and pass it to the view
$paginatedproducts= new LengthAwarePaginator($currentPageproducts , count($productCollection), $perPage);

// set url path for generted links
$paginatedproducts->setPath($request->url());

return view('products_view', ['products' => $paginatedproducts]);
}

--

--

Satyam.Conaxweb
Satyam.Conaxweb

Written by Satyam.Conaxweb

0 Followers

Technial Content Writer at Conaxweb Solutions Pvt. Ltd.

No responses yet