You can use simple math to paginate an array. Pick a page number and a page size. The page number tells you which part of the array you want. The page size tells you how many items to show.
In Laravel, pagination usually means getting data from a database and showing it in small, easy-to-read parts. But if you have an array with fixed data, you need to do things a bit differently.
In this guide, we’ll use Laravel’s LengthAwarePaginator and Collection to paginate a fixed array.
Let’s begin!
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
class ArrayPaginator {
public function paginate(array $data, array $query = [], int $perPage = 20): array
{
$request = request();
$pageName = $request->get('pageName', 'page');
$collection = $this->search(collect($data), $query);
$total = $collection->count();
$currentPage = $request->get($pageName, 1);
$options = [
'path' => $request->url() ?? '/',
'query' => $query,
'fragment' => $request->fragment ?? '',
'pageName' => $pageName,
];
$paginator = new LengthAwarePaginator($collection->forPage($currentPage, $perPage)->values()->all(), $total, $perPage, $currentPage, $options);
return $paginator->toArray();
}
public function search(Collection $data, array $filters = [])
{
foreach ($filters as $key => $value) {
if (is_array($value)) {
$data = $data->whereIn($key, $value);
} elseif (is_string($value)) {
$data = $data->filter(function ($item) use ($key, $value) {
return stripos($item[$key], $value) !== false;
});
} else {
$data = $data->where($key, $value);
}
}
return $data;
}
}
To get desired response call the paginate function
// Generate users
$users = [];
for ($i = 1; $i <= 1000; $i++) {
$users[] = [
'id' => $i,
'name' => "User $i",
'email' => "user{$i}@example.com",
'age' => rand(18, 67), // random age between 18 and 67
'city' => ['New York', 'Los Angeles', 'Chicago', 'Miami', 'Seattle', 'Austin', 'Philadelphia', 'Atlanta', 'Boston', 'Las Vegas'][array_rand(['New York', 'Los Angeles', 'Chicago', 'Miami', 'Seattle', 'Austin', 'Philadelphia', 'Atlanta', 'Boston', 'Las Vegas'])],
];
}
// to get 50 users per page
(new ArrayPaginator())->paginate($users, ['email' => '1@example'], 50);