Skip to content

Instantly share code, notes, and snippets.

@Artistan
Created August 6, 2018 13:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Artistan/ea9ed99c6ea04eb62384816391193616 to your computer and use it in GitHub Desktop.
Save Artistan/ea9ed99c6ea04eb62384816391193616 to your computer and use it in GitHub Desktop.
Upsert Eloquent Model
<?php
namespace My\Database;
trait Upsert {
/**
* @requires @param string $primaryKey
* OR
* @requires @param array $unique_keys
*
* will try using $unique_keys first, otherwise primaryKey to determine how to find existing record
* will take the rest of the data as the updatable data and run updateOrCreate on the Eloquent Model
*/
/**
* a smarter updateOrCreate
*
* @param array $allData
* @param bool $unique
* @return \Illuminate\Database\Eloquent\Model
*/
public function upsert($allData,$unique=true)
{
if ($unique && ! empty($this->unique_keys)) {
$keys = is_array($this->unique_keys) ? $this->unique_keys : [$this->unique_keys];
} else {
$keys = is_array($this->primaryKey) ? $this->primaryKey : [$this->primaryKey];
}
$unique_search = array_intersect_key($allData,array_combine($keys,$keys));
$updatable = array_diff_key($allData,$unique_search);
return parent::updateOrCreate($unique_search,$updatable);
}
}
<?php
namespace My\Database;
use Illuminate\Database\Eloquent\Model;
/**
* Class ModelNumberOne
*
* @package My\Database
*
* @mixin \Illuminate\Database\Eloquent\Concerns\QueriesRelationships
* @mixin \Illuminate\Database\Concerns\BuildsQueries
* @mixin \Illuminate\Database\Eloquent\Builder
*/
class ModelNumberOne extends Model
{
use Upsert;
protected $unique_keys = [
'owner_id',
'reference_id',
];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment