Check if record already exists, if already exists just link

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 it does not already exist I want to register the new address and then link. The relationship is 1 civilian has ONLY 1 address, and 1 address may have VARIOUS civilians. 1 - > N

I'm currently signing up this way, but it's generating duplicate zip codes:

        $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();

I thank you for your cooperation.

    
asked by anonymous 21.12.2017 / 17:08

1 answer

0

Thank you very much! I got it. The save() remains, I only needed to change the first line by firstOrNew , instead of $endereco = new endereco; I put: $endereco = endereco::firstOrNew(['cep' => $request->cep]); Thanks!

    
21.12.2017 / 20:10