neeonline's avatar

Pagination "Query\Builder could not be converted to string"

Hello all,

I have a query with pagination that I need to parse the data before returning it in my API. What is the method to force the paginate to get the results so I can navigate through the data object and not lose the pagination links?

This is an example code:

$result = DB::table('table')
    ->where('column', $filterValue);

if ($start && $end) {
    $start = Carbon::parse($start)->startOfDay()->format('Y-m-d H:i:s.u');
    $end = Carbon::parse($end)->endOfDay()->format('Y-m-d H:i:s.u');

    $result->where('datetime', '>=', $start)
        ->where('datetime', '<=', $end);
}

$result->orderBy('column', 'asc')
    ->paginate(1000);

// Do whatever with the data
//$result->data->each...

return $result;

First I cannot get the $result->data object so I can parse it.

Second, if I just return the $result, I got the error: "Object of class Illuminate\Database\Query\Builder could not be converted to string"

Can someone help me?

Thank you.

0 likes
3 replies
Cronix's avatar
Cronix
Best Answer
Level 67

try

$result = $result->orderBy('column', 'asc')
    ->paginate(1000);

return $result;
1 like
neeonline's avatar

@Cronix that did the trick. Now the $result is a Paginator object.

PSA: To access $result->items directly call the toArray function:

$result = $result->orderBy('column', 'asc')
    ->paginate(1000)
    ->toArray();

// Manipulate $result->data...

return $result;

Appreciate.

Cronix's avatar

You'd need to grab the collection off the paginated instance. It's not a normal model collection object since it's paginated and holds other data.

$result = $result->orderBy('column', 'asc')
    ->paginate(1000);

$items = $result->getCollection();

dd($items);

return $result;

Please or to participate in this conversation.