How can I paginate an array of objects in Laravel?

How can I paginate an array of objects in Laravel?

  1. Blog
  2. 15 November 2026
  3. 5 min read

Stefan Bogdanescu

Founder & Senior Architect

Paginating Published Units in Laravel Without Loading All Data

The core issue in your current approach isn't just that you're working with an array; it's that your query logic forces Laravel to load every single user and their entire relationship graph into memory before you can even attempt to filter or sort the results. You are iterating through $users, then looping through their units, checking pivot data, and manually manipulating the resulting collection with array_unshift and array_push. This pattern breaks pagination because it prevents the database from handling the limiting and offsetting logic efficiently.

To paginate this specific scenario—filtering by publish == 1, unit_purpose_id == 1, and sorting by adtype—you need to shift the filtering responsibility back to the database. The database is designed to handle complex joins, where clauses, and ordering operations on millions of rows; doing this in PHP loops destroys performance and memory efficiency.

Using Eloquent Query Scopes

The cleanest architectural solution is to define a reusable scope within your Unit model. This allows you to express the filtering logic once and apply it anywhere you need published units, regardless of whether you are paginating or not.

Add a public scope method to your Unit model:

public function scopePublished($query)
{
    return $query->where('units.purpose_id', 1)
                  ->wherePivot('publish', 1)
                  ->orderBy('adtype', 'desc');
}

This method accepts a query builder instance and chains the necessary constraints. Note that wherePivot is specific to Eloquent relationships. Since your units model has a belongsToMany relationship with the User model, you can leverage this relationship in your query.

Constructing the Paginated Query

Instead of fetching all users first, you should query the Unit model directly, joining with the pivot table to apply your filters. Assuming your Unit model has a belongsToMany('User', 'user_units') relationship (as defined in your source code), you can construct the query like this:

$publishedSaleUnits = User::with(['units' => function ($query) {
    $query->published();
}])
      ->get()
      ->flatMap(function ($user) {
          return $user->units;
      })
      ->filter(fn ($unit) => $unit->pivot->publish == 1 && $unit->unit_purpose_id == 1)
      ->values(); // Reset keys if necessary after filtering

Wait, that approach still loads all users. The most efficient method is to query the pivot table directly or use a join on the main units table if you don't strictly need the User model attached for every single item in the paginated list.

However, if you must maintain the relationship to access user data alongside the units, consider querying the pivot table directly using Eloquent's raw capabilities or a specific scope on the Unit model that ignores the user side entirely for the initial fetch.

A more direct approach without loading all users first:

$publishedSaleUnits = Unit::with(['users' => function ($query) {
    $query->whereHas('units', function ($q) {
        // This ensures we only get units where the relationship exists
    });
}])
      ->published() // Assuming the scope defined above applies to units table
      ->paginate(20);

Actually, the most robust solution given your schema is to query the user_units pivot table directly if you need specific pivot filtering, or use a join. But since you are using Eloquent relationships, let's refine the scope to work on the main model without requiring a user loop.

If the requirement is strictly "published units by all users," and you don't need the User object attached to every Unit in the result set (which is often the case for simple listing pages), you can query the Unit model with a join:

$publishedSaleUnits = Unit::join('user_units', 'units.id', '=', 'user_units.unit_id')
    ->where('user_units.publish', 1)
    ->where('units.purpose_id', 1)
    ->orderBy('user_units.adtype', 'desc')
    ->paginate(20);

This query returns a LengthAwarePaginator object. You can access the items via $publishedSaleUnits->items() and include the pivot data in the relationship if needed, though accessing pivot columns on paginated models sometimes requires eager loading or raw attributes depending on how the results are cast.

Handling Pivot Data in Paginated Results

One common pitfall when paginating is ensuring that pivot properties are accessible. In standard Eloquent pagination, accessing $unit->pivot->publish works if you have eager loaded the relationship. However, if you query the Unit table directly via a join (as shown above), the model might not automatically load the pivot columns unless configured.

To ensure pivot data is available on every paginated item without overloading memory, you can use withPivot:

$publishedSaleUnits = Unit::join('user_units', 'units.id', '=', 'user_units.unit_id')
    ->withPivot(['publish', 'adtype', 'addinfo']) // Explicitly request pivot columns
    ->where('user_units.publish', 1)
    ->where('units.purpose_id', 1)
    ->orderBy('user_units.adtype', 'desc')
    ->paginate(20);

By using withPivot, you tell Eloquent to include those specific columns from the joined table in the model's attributes, allowing you to access $unit->pivot->publish safely within your Blade template or controller logic.

Avoiding Manual Array Manipulation

Your original code used array_unshift and array_push to separate featured ads from normal ones. While this works for a flat array, it is inefficient for large datasets. If you need to prioritize certain types of ads in the pagination output, consider using Laravel's query builder ordering capabilities or sorting the paginated collection in memory only after retrieving the page:

$items = $publishedSaleUnits->items();

// Separate featured and normal within the current page context
$featured = [];
$normal = [];

foreach ($items as $unit) {
    if ($unit->pivot->adtype === 'featured') {
        array_unshift($featured, $unit); // Or use a separate collection for rendering
    } else {
        array_push($normal, $unit);
    }
}

While this manual separation still happens in memory, it is scoped to the current page's size (e.g., 20 items) rather than the entire dataset. This is acceptable for UI prioritization but should not be used to filter the initial database query results if performance is critical at scale.

For large-scale applications involving millions of records, always let the database handle filtering and sorting first. Only perform complex business logic separations on the final, paginated result set in memory.

Our network