120+ Engineers
20+ Countries
850+ Projects
750+ Satisfied Clients
4.9 Clutch
120+ Engineers
20+ Countries
850+ Projects
750+ Satisfied Clients
4.9 Clutch
120+ Engineers
20+ Countries
850+ Projects
750+ Satisfied Clients

Laravel pagination and filtering with already loaded data as array in memory

Learn the essential skills and steps to become a full stack developer. Start your journey today with this comprehensive guide for beginners!

Last Update: 10 Oct 2024

Laravel pagination and filtering with already loaded data as array in memory image

How to Paginate a Large Array

When working with a large array in code, it's important to break it down into smaller pieces. This makes the data easier to handle. The process of breaking it into smaller parts is called pagination.

What is Pagination?

Pagination splits a big list into smaller pages. Each page shows only a part of the full list. You can decide how many items go on each page.

Why Use Pagination?

When you load too much data at once, your system can slow down. Pagination helps by loading only what you need.

 

How to make array paginator with filter?

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);

Pros of Array Pagination

  • Faster Loading: Smaller chunks of data load faster than a huge list.
  • Better User Experience: Users don’t have to scroll through long lists. They can see a few items at a time.
  • Organized Data: Breaking up the data into pages makes it easier to read and manage.

Cons of Array Pagination

  • More Code: You need extra logic to handle page numbers and sizes.
  • Data Shifts: If the data changes while paginating, users might see incorrect pages.
  • Navigation Can Be Slow: Users have to click through pages, which can be slower than scrolling.
  • Limits Large Searches: Pagination can make it harder to filter or sort large arrays quickly.

 

Frequently Asked Questions

Trendingblogs
Get the best of our content straight to your inbox!

By submitting, you agree to our privacy policy.

Have a Project To Discuss?

We're ready!

Let's
Talk