get(); $groupedBanks = $records->groupBy(function($item, $key) { return $item['company_id'] . '-' . $item['account_no']; }); foreach ($groupedBanks as $key => $banksWithSameUserAndAccountNo) { // Sort banks by created_at or updated_at to find the latest one $sortedBanks = $banksWithSameUserAndAccountNo->sortByDesc('created_at'); // Retain the latest bank $latestBank = $sortedBanks->first(); // Get all IDs except the latest one $idsToDelete = $sortedBanks->pluck('id')->slice(1); foreach ($idsToDelete as $id) { Booking::where('bank_id', $id)->update([ 'bank_id' => $latestBank->id ]); } $this->info('for company id: ' . $latestBank->company_id . ', account no: ' . $latestBank->account_no . ', duplicated id: ' . $idsToDelete); // Delete the rest Bank::whereIn('id', $idsToDelete)->delete(); } } }