laravellaravel-pagination

How do I get a list of orders with pagination in Laravel 9?


"$dbOrderStatusArray" Returns an array with data

$dbOrderStatusArray = SitesOrderStatus::where("internal_status_id", 2)->select("site_id", "order_status_id")->get()->toArray();

An example of the received data is below.

$dbOrderStatusArray = [
    ["site_id" => 7230,"order_status_id" => 17],
    ["site_id" => 7230,"order_status_id" => 23],
    ["site_id" => 7230,"order_status_id" => 25],
    ["site_id" => 3881,"order_status_id" => 2],
    ["site_id" => 3881,"order_status_id" => 19],
    ["site_id" => 3881,"order_status_id" => 17]
];

I'm trying to get a list by order by getting data and collecting them. Then I want to add sorting and pagination. But no matter how hard I try I get one of the errors.

Method Illuminate\Support\Collection::paginate does not exist.
or
Method Illuminate\Support\Collection::links does not exist..

$orders = collect([]);
foreach ($dbOrderStatusArray as $item) {
$orders = $orders->concat(SitesOrders::where('site_id', $item['site_id'])->where('order_status_id', $item['order_status_id'])->get());
}

$paginate = $orders->sortByDesc('date_added')->paginate($data['paginate']);

$data['orders'] = $paginate;

Perhaps someone has come across this problem and can help? At the beginning, I get the order statuses of all stores that have id 2 of the internal site status.


Solution

  • In your version of laravel, You cannot run paginate() on a Collection instance. It should be used on a QueryBuilder instance.

    $orders = SitesOrders::query();
    foreach ($dbOrderStatusArray as $item) {
        $orders->orWhere(function($query) use ($item) {
            $query->where('site_id', $item['site_id'])->where('order_status_id', $item['order_status_id']);
        });
    }
    
    $paginate = $orders->sortByDesc('date_added')->paginate($data['paginate']);
    
    $data['orders'] = $paginate;