Skip to content

Instantly share code, notes, and snippets.

@kdes70
Created June 17, 2022 09:50
Show Gist options
  • Save kdes70/3bb45e562b100b4d97c979d8ee4dc2a8 to your computer and use it in GitHub Desktop.
Save kdes70/3bb45e562b100b4d97c979d8ee4dc2a8 to your computer and use it in GitHub Desktop.
Mass (bulk) insert or update on duplicate for Laravel 4/5
<?php
namespace Crm\Repositories\Traits;
trait MassInsertOrUpdate {
/**
* Mass (bulk) insert or update on duplicate for Laravel 4/5
*
* insertOrUpdate([
* ['id'=>1,'value'=>10],
* ['id'=>2,'value'=>60]
* ]);
*
*/
function insertOrUpdate(array $rows): bool {
$table = \DB::getTablePrefix() . with($this->model)->getTable();
$firstRow = reset($rows);
$columns = $this->getColumns($firstRow);
$values = $this->getValues($rows);
$updates = $this->getUpdates($firstRow);
$sql = "INSERT INTO {$table}({$columns}) VALUES {$values} ON DUPLICATE KEY UPDATE {$updates}";
return \DB::statement($sql);
}
private function getColumns(array $firstRow): string {
return implode(',', array_map(function ($value) {
return "$value";
}, array_keys($firstRow))
);
}
private function getValues(array $rows): string {
return implode(',', array_map(function ($row) {
return '(' . implode(',',
array_map(function ($value) {
return '"' . str_replace('"', '""', $value) . '"';
}, $row)
) . ')';
}, $rows)
);
}
private function getUpdates(array $firstRow): string {
implode(',',
array_map(function ($value) {
return "$value = VALUES($value)";
}, array_keys($firstRow))
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment