Artisan Command - Foreach Laravel - Count affected lines

Asked

Viewed 74 times

0

I created a command in Laravel to run at a certain time and now I need to get the result only of the affected lines. The method I used makes a count of the entire loop.

$count = 0;
foreach ($contacts as $contact) {
if (empty($contact->nome))
continue;
if (empty($contact->cnpj))
continue;

$contato = $company->clientes()->updateOrCreate([
'cpf_cnpj'          => $contact->cnpj
], [
 'cpf_cnpj'          => $contact->cnpj,
 'company_id'        => $company->id,
 'nome'              => $contact->nome,
 'fantasia'          => $contact->fantasia,
 'tipo'              => $contact->tipo,
 'ie_rg'             => $contact->ie_rg,
 'endereco'          => $contact->endereco,
 'numero'            => $contact->numero,
 'bairro'            => $contact->bairro,
 'cep'               => $contact->cep,
 'cidade'            => $contact->cidade,
 'complemento'       => $contact->complemento,
 'uf'                => $contact->uf,
 'fone_cell'         => $contact->fone,
 'email'             => $contact->email,
 'limiteCredito'     => $contact->limiteCredito,
 'situacao'          => $contact->situacao,
 'contribuinte'      => $contact->contribuinte,
 'dataNascimento'    => isset($contact->dataNascimento[0]) ? $contact->dataNascimento : null
]);
 $count++;
 $contato->save();
}

2 answers

1

I don’t know if I understand your question correctly, but if you want to know which fields were changed in the variable $contato (in the case of the outcome of updateOrCreate for an edition, in the creation it will not work), just use the getChanges():

$contato->getChanges();
# ['bairro' => 'Nome do bairro alterado']

If you really want to know the line in the file that was changed... I don’t think it’s good practice, because if more fields are added, you’ll have to worry about mapping the attribute with the line.

-1

I believe the result of update or create will generate an object from ORM in the variable $contato, in this case it may be possible to use the count() in the same:

$contato->count();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.