Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

firestruck's avatar

Pagination on array

Hi, i need to do pagination in this query: In Eloquent Queries i use $query->paginate(10)

But in this query i can´t because it´s an array(even after convert to object , i cant implement ->paginate or ->get():

My code:


 $results = DB::select('select u.id,u.`name`,r.title, r.start_time,  r.end_time, r.estado from `users` u
inner join
(select user_id, title,start_time, end_time, 4 AS estado FROM `canceled`
union all
select user_id, title,start_time, end_time, 1 AS estado FROM `events`
union all
select user_id,title, start_time, end_time, 2 AS estado FROM `confirmed`
union all
select user_id,title, start_time, end_time, 3 AS estado FROM `replaced`
union all
select user_id,title, start_time, end_time, 5 AS estado FROM `schedule`
) r on u.id = r.user_id
WHERE r.estado = 2');
    $results = collect($results);

```

0 likes
2 replies
silverxjohn's avatar

@firestruck, You could implement a paginator yourself with Laravel's LengthAwarePagination.

Here's the signature of its constructor:

public function __construct($items, $total, $perPage, $currentPage = null, array $options = [])

We are interested in the first four arguments. So when we instantiate a new instance of LengthAwarePagination, we need to pass these parameters:

// whatever is the result of your query that you wish to paginate.
$items = [];

// The total number of items. If the `$items` has all the data, you can do something like this:
$total = count($items);

// How many items do you want to display.
$perPage = 5;

// The index page.
$currentPage = 1;

$paginator = new Illuminate\Pagination\LengthAwarePaginator($items, $total, $perPage, $currentPage)

If you're requesting the data from ajax, you can return it from your controller

return Response::json($paginator);

and it will return a JSON object:

{
    'current_page': 'your/url/2',
    'data' => [{Object object, Object object}], // This is where your data lives.
    'from' => 1,
    'last_page' => 12,
    'next_page_url' => 'your/url/3',
    'path' => 'your/url',
    'per_page' => 5,
    'prev_page_url' => 'your/url/1',
    'to' => 60,
    'total' => 60
}

If you want to display the buttons for pagination to your Blade:

<div class="row">
    {{ $paginator->links() }}
</div>

PS. This is just a quick example I made. I didn't run/build this so you might find silly errors. But if you're stuck, check the documentation here: https://laravel.com/docs/5.4/pagination#manually-creating-a-paginator

It's a good practice to check the actual class when trying to tinker around. You can check the LengthAwarePaginator here https://github.com/illuminate/pagination/blob/master/LengthAwarePaginator.php

2 likes

Please or to participate in this conversation.