5 months ago

FirstOrCreate not able to find the data. Duplicate entry for Key SQL Exception

Posted 5 months ago by Alexb0903

Hi everyone

I have made an application that retrieve the lead from a Facebook Page by doing some API calls. In my database, I have a field 'fb_lead_id' that is a unique key because every facebook lead has his own id. That way when i download lead again, The Eloquent model were able to only download the new lead and avoid duplicate. Every thing was working fine when doing some manual download only (clicking a button).

Our boss asked us to implement the facebook webhook of the lead so that they would go automatically in the database. Since then, the leads received from the webhook are going in the database but it is now impossible to do some manual download because the firstOrCreate method doesn't seem to reconize that it's the same lead as the one already in the database via the webhook.

I always get this error

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '454473502074158' for key 'facebook_leads_fb_lead_id_unique' (SQL: insert into `facebook_leads` (`fb_lead_id`, `facebook_form_fk`, `facebook_campaign_fk`, `facebook_ad_fk`, `platform`, `created_at`, `updated_at`) values (454473502074158, 155, 258, 1072, Facebook, 2019-08-13 13:25:15, 2019-08-13 13:28:36))

Is there a way to do some kind of insert or ignore ? Here is my FacebookLead Model where the createFacebookLeadInDb method is used to create the lead

protected $table = "facebook_leads";
    protected $fillable = [

    public static function createFacebookLeadInDb($leadJson,$formId,$newCampaignId, $newAdId,$campaignPlatform){
        $campaignPlatform = ($campaignPlatform == 'fb') ? 'Facebook' : 'Instagram';
        $newLead = self::updateOrCreate([
            'fb_lead_id' => $leadJson['id'],
            'facebook_form_fk' => $formId,
            'facebook_campaign_fk' => (isset($newCampaignId)) ? $newCampaignId : null,
            'facebook_ad_fk' => (isset($newAdId))? $newAdId : null,
            'platform' => $campaignPlatform,
            'created_at' => $leadJson['created_time']
        return $newLead->id;
    public function form() {
        return $this->belongsTo('App\FacebookForm',"facebook_form_fk","id");

    public function leadsMapping() {
        return $this->hasMany('App\FacebookLeadMapping','facebook_lead_fk', "id");
    public function ad() {
        return $this->belongsTo('App\FacebookAd', "facebook_ad_fk", 'id');

    public function getAdId() {
        try {
            return $this->ad->facebook_ad_id;
        } catch(\Exception $e){
            //The lead  as no campaign and thus no ad
            return null;

Please sign in or create an account to participate in this conversation.