Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

umerfayyaz's avatar

Duplicate entry in table in laravel

Hi i am facing an issue through loop i am sending email but it save record two time or 4times also in table. i also add check if rec is null then it do an entry here it is my code

DB::table('sendportal_subscribers')->where('unsubscribed_at',NULL)->orderBy('id')->chunk(300, function ($subscribers) use ($template_campaign,$campaign) {
                    foreach ($subscribers as $subscriber) {
                        
                        $check = DB::table('sendportal_messages')->where(['source_id'=>$campaign->id,'subscriber_id' => $subscriber->id,'recipient_email'=>$subscriber->email])->first();
                        if (is_null($check)) {

                           
                           //save entry
                           $data = [

                               'hash'=> Hash::make($subscriber->email),
                               'workspace_id'=>1,
                               'subscriber_id' => $subscriber->id,
                               'source_type'=>'Sendportal\Base\Models\Campaign',
                               'source_id' => $campaign->id,
                               'recipient_email'=> $subscriber->email,
                               'subject'=> $campaign->name,
                               'from_name'=> $campaign->from_name,
                               'from_email'=>$campaign->from_email,
                               'open_count'=>0,
                               'click_count'=>0,
                               'sent_at'=>now(),
                               'created_at'=>now()
                           ];    
                           DB::table('sendportal_messages')->insert($data);
						 //send mail 
                           sendEmailCampaignJob::dispatch($subscriber->email ,$campaign->subject);
				}

here it is table data lara.png

it store 4 times record in table for same entry Thanks for any help

0 likes
3 replies
AungHtetPaing__'s avatar

@umerfayyaz I think multi where clause should be like this

->where([
['source_id'=>$campaign->id],
['subscriber_id' => $subscriber->id],
['recipient_email'=>$subscriber->email],
])

Edited

->where([
['source_id', $campaign->id],
['subscriber_id', $subscriber->id],
['recipient_email',$subscriber->email], 
])
1 like
AungHtetPaing__'s avatar

@umerfayyaz I don't see other problem rather than where clause syntax. Are you sure the condition check work as expected? Check $check what you get if data already exists. You can also use exists() instead of first() which return true or false no need is_null.

Please or to participate in this conversation.