Skip to content

Instantly share code, notes, and snippets.

@cosmastech
Created December 23, 2023 17:24
Show Gist options
  • Save cosmastech/bfd6d060df602d3fed1f3982febb5305 to your computer and use it in GitHub Desktop.
Save cosmastech/bfd6d060df602d3fed1f3982febb5305 to your computer and use it in GitHub Desktop.
Insert With Casts Example
<?php
use Illuminate\Database\Eloquent\Builder;
class BaseEloquentBuilder extends Builder
{
public function insertWithCasts(iterable $values): bool
{
if (empty($values)) {
return true;
}
if (! is_array(reset($values))) {
$values = [$values];
}
$modelInstance = $this->newModelInstance();
$timestampColumns = [];
if ($modelInstance->usesTimestamps()) {
$now = $modelInstance->freshTimestamp();
if ($createdAtColumn = $modelInstance->getCreatedAtColumn()) {
$timestampColumns[$createdAtColumn] = $now;
}
if ($updatedAtColumn = $modelInstance->getUpdatedAtColumn()) {
$timestampColumns[$updatedAtColumn] = $now;
}
}
$this->model->unguarded(function () use (&$values, $timestampColumns) {
foreach ($values as $key => $value) {
$values[$key] = $this->newModelInstance(array_merge($timestampColumns, $value))->getAttributes();
}
});
return $this->toBase()->insert($values);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment