city_id ..." list. A missing bank usually means its Location has no city_id set -- fix that on the bank's profile first, then re-run the dry-run before applying. See references/BANK_CLIENTS_BACKFILL_COMMAND.md for full documentation. HELP; public function handle(): int { $dryRun = (bool) $this->option('dry-run'); $banks = Bank::where('level', 2)->get()->filter(function (Bank $bank) { return (bool) $bank->locations()->whereNotNull('city_id')->exists(); }); if ($banks->isEmpty()) { $this->error('No level-2 banks with a city_id location found. Nothing to do.'); return self::FAILURE; } $bankCityMap = []; foreach ($banks as $bank) { $cityId = $bank->locations()->whereNotNull('city_id')->value('city_id'); $bankCityMap[$cityId] = $bank; $this->line("Bank #{$bank->id} \"{$bank->name}\" -> city_id {$cityId}"); } $cityIds = array_keys($bankCityMap); $this->newLine(); $this->info($dryRun ? 'DRY RUN — no changes will be written.' : 'Writing bank_clients rows.'); $this->newLine(); $totalLinked = 0; $totalSkippedAlreadyLinked = 0; foreach (['user' => User::class, 'organization' => Organization::class] as $label => $modelClass) { $matches = Location::where('locatable_type', $modelClass) ->whereIn('city_id', $cityIds) ->get(['locatable_id', 'city_id']); $this->info(ucfirst($label) . "s matched by city: {$matches->count()}"); $bar = $this->output->createProgressBar($matches->count()); $bar->start(); foreach ($matches as $location) { $bank = $bankCityMap[$location->city_id]; $client = $modelClass::find($location->locatable_id); if (!$client) { $bar->advance(); continue; } $alreadyLinked = $client->banksClient()->exists(); if ($alreadyLinked) { $totalSkippedAlreadyLinked++; $bar->advance(); continue; } if (!$dryRun) { $client->attachBankClient($bank, 'local'); } $totalLinked++; $bar->advance(); } $bar->finish(); $this->newLine(2); } $this->info("Linked: {$totalLinked}"); $this->info("Skipped (already linked): {$totalSkippedAlreadyLinked}"); if ($dryRun) { $this->comment('Run without --dry-run to apply these changes.'); } return self::SUCCESS; } }