Check if registration already exists, if there is only link

Asked

Viewed 378 times

0

I want to check if the address has already been registered, if it is already registered I just want to link it to a civilian, but if there is not yet want to register the new address and then link. The relationship is 1 civil has ONLY 1 address, and 1 address can have SEVERAL civilians. 1 -> N

At the moment I am registering this way, but is generating duplicate CEP’S:

        $endereco = new endereco;
        $endereco->complemento = $request->complemento;
        $endereco->logradouro = $request->logradouro;
        $endereco->bairro = $request->bairro;
        $endereco->cidade = $request->cidade;
        $endereco->estado_uf = $request->uf;
        $endereco->cep = $request->cep;
        $endereco->save();   

        $civil = new civil;
        $civil->nome = $request->nome;
        $civil->cpf = $request->cpf;
        $civil->matricula = $request->matricula;
        $civil->data_nascimento = $request->data_nascimento;
        $civil->pai = $request->pai;
        $civil->mae = $request->mae;
        $civil->situacao = $request->situacao;
        $civil->sexo = $request->sexo;
        $civil->matricula = $request->matricula;
        $civil->estado_civil = $request->estado_civil;
        $civil->endereco_id = $endereco->id;
        $civil->save();

Thanks for your cooperation.

1 answer

1

Thank you so much! I got it. The save() remains, I only had to exchange the first line for the firstOrNew, instead of $endereco = new endereco; placed: $endereco = endereco::firstOrNew(['cep' => $request->cep]); Thank you very much!!!

Browser other questions tagged

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