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 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]); } }
Also Read: Laravel Pagination with Ajax
// In your view
<h1>Products List</h1> <pre> <ul> @foreach ($products as $product) <li> {{ $product }} </li> @endforeach </ul> <div> {{ $products->links() }} </div>
//In your Routes
Route::get('products','ProductsController@items');