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

Jonjie's avatar
Level 12

How to add offset after sortBy in laravel

How can I add offset after using sortBy in laravel? Please see my code below.

Controller

$order_type = ($dir == 'asc') ? 'sortBy' : 'sortByDesc';
$inventories = $inventories->get()->$order_type(function($inventory) {
            $item_status = [
                '0'  => 'I',
                '1'  => 'D',
                '2' => 'HI',
                '3' => 'HR',
                '4' => 'A',
                '5' => 'DS'
            ];

	return $item_status[$inventory->receive_item->inspection_status];
});

$inventories = $inventories->offset($start)->limit($limit);

Error I get

BadMethodCallException in Macroable.php line 74: Method offset does not exist.

0 likes
3 replies
Jonjie's avatar
Level 12

I have to sort it by child table so I tried the orderBy using eager loading like this:

$inventories = $inventories->with([
        'receive_item' => function($query) {
        return $query->select('*')->orderBy('inspection_status', request('order.0.dir'));
}])

But Im getting the same result.

Please or to participate in this conversation.