I am using Laravel 5.6.29
if ( HarmFlag::where('post_id', '=', $postId)->where('harm_id', '=', $harm_id)->get()->isEmpty() ) {
HarmFlag::create([
'post_id' => $postId,
'harm_id' => $harm_id,
'gif_flag' => $gif_flag
]);
} else {
$harmFlag = HarmFlag::where('post_id', '=', $postId)->where('harm_id', '=', $harm_id)->first();
$harmFlag->gif_flag = $gif_flag;
$harmFlag->save();
}
Now it can be seen there are duplicate records for harm_id=18604
and harm_id=18605
, but according to what I have coded, it should not happen.
Update
Also changed the code to
$harmFlag = HarmFlag::firstOrNew(['post_id' => $postId, 'harm_id' => $harm_id]);
$harmFlag->gif_flag = $gif_flag;
$harmFlag->save();
but still getting duplicate entries.
Interesting fact about this is for every duplicate records, the timestamp is also same. As well there is only a second record for all these situation.
Migration
Schema::create('harm_flags', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('post_id');
$table->unsignedInteger('harm_id');
$table->boolean('gif_flag')->default(0);
$table->timestamps();
$table->foreign('post_id')->references('post_id')->on('posts');
$table->foreign('harm_id')->references('harm_id')->on('base_harms');
});
Update 2
changed to
HarmFlag::updateOrCreate(
['post_id' => $postId, 'harm_id' => $harm_id],
[
'gif_flag' => $gif_flag,
]
);
but still getting duplicate records.
You don't need to check isEmpty
, you can use firstOrNew()
or updateOrCreate()
methods
$harmFlag = HarmFlag::firstOrNew(['post_id' => $postId, 'harm_id' => $harm_id]);
$harmFlag->gif_flag = $gif_flag;
$harmFlag->save();
or
$harmFlag = HarmFlag::updateOrCreate(['post_id' => $postId, 'harm_id' => $harm_id]);
$harmFlag->gif_flag = $gif_flag;
$harmFlag->save();
please check the document https://laravel.com/docs/5.3/eloquent#insert-update-delete
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With