format('Ymd'); // Fetch last order (including soft-deleted) $lastOrder = DB::table('orders') ->where('restaurant_id', $restaurantId) ->whereDate('created_at', Carbon::today()) ->orderByDesc('id') ->first(); $lastIncrement = 0; if ($lastOrder && preg_match('/ORD-\d{8}-\d+-([\d]+)/', $lastOrder->order_number, $matches)) { $lastIncrement = (int) $matches[1]; } $newIncrement = $lastIncrement + 1; // Ensure unique, retry if needed (handles rare race conditions) do { $orderNumber = sprintf('ORD-%s-%d-%04d', $today, $restaurantId, $newIncrement); $exists = Order::withTrashed()->where('order_number', $orderNumber)->exists(); if ($exists) { $newIncrement++; } } while ($exists); return $orderNumber; } }