Creating Custom Pagination from an Array in Laravel
Laravel provides excellent pagination tools for database queries, but sometimes you need to paginate a regular array. Here's how to create custom pagination from an array in Laravel:
Method 1: Using Laravel's Paginator
php
use Illuminate\Pagination\LengthAwarePaginator; use Illuminate\Pagination\Paginator; use Illuminate\Support\Collection; // Your original array $items = ['item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item7']; // Current page (default to 1 if not set) $currentPage = LengthAwarePaginator::resolveCurrentPage(); // Number of items per page $perPage = 3; // Slice the array to get the items to display $currentItems = array_slice($items, ($currentPage - 1) * $perPage, $perPage); // Create our paginator $paginatedItems = new LengthAwarePaginator( $currentItems, count($items), $perPage, $currentPage, [ 'path' => LengthAwarePaginator::resolveCurrentPath() ] );
Method 2: Using Collections (Laravel 8+)
php
use Illuminate\Pagination\Paginator; // Convert array to collection $collection = collect(['item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item7']); // Paginate the collection $perPage = 3; $currentPage = Paginator::resolveCurrentPage() ?: 1; $paginatedItems = $collection->slice(($currentPage - 1) * $perPage, $perPage)->all(); $paginator = new LengthAwarePaginator( $paginatedItems, $collection->count(), $perPage, $currentPage, ['path' => Paginator::resolveCurrentPath()] );
Method 3: Using a Helper Function
You can create a helper function in your app to reuse this functionality:
php
function paginateArray($items, $perPage = 15, $page = null, $options = []) { $page = $page ?: (Paginator::resolveCurrentPage() ?: 1); $items = $items instanceof Collection ? $items : Collection::make($items); return new LengthAwarePaginator( $items->forPage($page, $perPage), $items->count(), $perPage, $page, $options ); } // Then use it like this: $paginatedItems = paginateArray($yourArray, 5);
Displaying in Blade
In your Blade view, you can display the paginated items and links:
php
@foreach($paginatedItems as $item) <div>{{ $item }}</div> @endforeach {{ $paginatedItems->links() }}
Customizing the Pagination View
If you want to customize how the pagination links look:
Publish the pagination views:
php artisan vendor:publish --tag=laravel-pagination
Then modify the views in
resources/views/vendor/pagination/