databaselaravelinserteloquentduplicate-data

On existing record skip otherwise insert data Laravel Eloquent


I have the following table structure which I seed dynamically from API

public function up() {
    Schema::create('reports', function(Blueprint $table) {
        $table->engine = 'InnoDB';
        $table->increments('id');
        $table->integer('program_id')->unique();
        $table->date('date');
        .
        .
        .
        $table->timestamps();
    });

on each API request I get back an array of Data and I try to save theme in the table above. If program_id exist I would like to ignore those records and save the new one. I've been looking around but I do not find the best way the validate the specific value in retrieved array

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '528027827' for key 'reports_program_id_unique

The way as I save my records

// $datas are the field datas from API
foreach ($datas as $data) 
{
      $report = \Td\Reports\Reports\Reports::firstOrCreate($data);
}

How to skip insert on existing program_id and insert just the new ones?


Solution

  • You can use firstOrCreate():

    $data = ['program_id' => 528027827, ...];
    
    $report = Report::firstOrCreate($data);