Home > OS >  How to prevent duplicates in Laravel Eloquent?
How to prevent duplicates in Laravel Eloquent?

Time:11-14

I want to transform my database entry creation inside NewsletterController.php:

$email = $request->input('email');
$table = DB::table('newsletters');
$table->insert(array('email' => $email, 'created_at' => now()));

to prevent duplicate entries. I tried doing this:

$table = DB::updateOrCreate('newsletters');

but this method does not seem to exist for DB. How would I do that?

CodePudding user response:

updateOrCreate you use for Eloquent Builder and updateOrInsert you use for Query Builder. Try with updateOrInsert.

$table = DB::updateOrInsert->table('newsletters')->([ 'id' => $request->id ], [
  'email' => $email,
]);

CodePudding user response:

when you may want to update an existing record in the database or create it if no matching record exists. In this scenario, the updateOrInsert method may be used. The updateOrInsert method accepts two arguments: an array of conditions by which to find the record, and an array of column and value pairs indicating the columns to be updated.

The updateOrInsert method will attempt to locate a matching database record using the first argument's column and value pairs. If the record exists, it will be updated with the values in the second argument. If the record can not be found, a new record will be inserted with the merged attributes of both arguments

 DB::updateOrInsert(['email'=>$eamil],['created_at'=>Carbon::now()]);

now, if email exists, the 'created_at' will be updated, otherwise a new row will be inserted with values of the merged array arguments

CodePudding user response:

Thanks to Moussab Kbeisy's comment I can validate for uniqueness which will return a 422 error if not met instead of inserting into the database:

$this->validate($request, [
    'email' => 'required | unique:newsletters'
]);

$email = $request->input('email');
$table = DB::table('newsletters');
$table->insert(['email' => $email, 'created_at' => now()]);
  • Related