How to insert value in BD only if it does not exist, using Laravel

Asked

Viewed 273 times

0

I’m trying to automatically register a value in the database using Laravel. I’m struggling to think of an efficient solution to this. Below is the example of what I want.

    $email = '[email protected]';

    MeuModel::create(array_merge($request->all(), ['email'=>$email] ));

My logic is this:: As long as the value of $email within the database, register the value of the $email. If the value of $email is in the database, do not register this value. I want to find the solution using the models from Laravel. You could help me?

2 answers

1

You can use a if as follows:

$data = $request->all();

// Só vai entrar no if se ele encontrar algum registro
if (!$user = User::where('email', $data['email'])->first()) {
    $user = User::create($data);
    return $user;
}

// Se já existir um usuário você pode atualizar as informações
$user->fill($data)->save();

return $user;

0


Take a look here man: https://laravel.com/docs/5.5/eloquent#retrieving-single-models

If what matters is email, you can use:

MeuModel::firstOrCreate(['email' => '[email protected]']);

using the $request:

MeuModel::firstOrCreate($request->except(['retire_chave_desnecessária']));

or

MeuModel::firstOrCreate($request->only(['quero_chave1', 'quero_chave2',...]));

whenever nothing is found, a new record will be created and returned.

Already with the method:

$x = MeuModel::firstOrNew(['nome_do_campo' => 'valor_do_campo_que_estou_buscando']);

if there is any record of the data you are looking for, it will be returned. If it does not exist, you will receive an object of type Meumodel $x already with the die set:

$x->nome_do_campo = 'valor_do_campo_que_estou_buscando';

in sequence you NEED to call save:

$x->save();

now you persisted and can tell more this Meumodel in the bank. If you have $table->timestamp() in the Meumodel Migration, then do so:

$x = MeuModel::firstOrNew(['nome_do_campo' => 'valor_do_campo_que_estou_buscando']);

if(empty($x->created_at)) {
    $x->save();
}
  • The method firstOrCreate() only works if the data is all the same, for example if you try to insert ['name' => 'Fulano', 'email' => '[email protected]'] but in your database already exists the email "[email protected]" but his name is saved as "Fulano Silva", the method firstOrCreate() will understand how 2 different records and will save duplicate email in your bank.

  • Emmanuel, your answer was helpful. Try to develop it better for me to give you a positive.

Browser other questions tagged

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