How to move First/Selected order to last in Laravel?

I want to move my first order to the bottom of the list and not to delete the first order as well. here is my code. This is deleting/unset first order as well.

`

if (isset($request['defer_order']) && $request['defer_order'] != null) {
            $order_id = $request['defer_order'];

            foreach ($order_items as $key => $order_item) {
                $last = count($order_items);
                if ($order_item->order_id == $order_id) {
                    unset($order_items[$key]);
                    $order_items[$last + 1] = $order_item;

                }
            }


            $order_items = $order_items;

        }

`

I am trying to move first order to the bottom of the list.

Upvotes: 0

Views: 66

Answers (1)

M. Haseeb Akhtar
M. Haseeb Akhtar

Reputation: 867

Since you are using unset, the order is removed from the array. You can use the code below instead. It will add your desired order at the end without changing anything in the array

if (isset($request['defer_order']) && $request['defer_order'] != null) {
    $order_id = $request['defer_order'];

    $order_items = (array)$order_items;

    $myOrder = '';
    foreach ($order_items as $order_item) {
        if ($order_item['order_id'] == $order_id) {
            $myOrder = $order_item;
            unset($order_items[$key]);

            break;
        }
    }

    if ($myOrder != '') {
        $order_items[] = $myOrder;
    }

    $order_items = (object)$order_items;
}

Updated the code as per your requirement

Upvotes: 1

Related Questions