Created
December 23, 2023 17:24
-
-
Save cosmastech/bfd6d060df602d3fed1f3982febb5305 to your computer and use it in GitHub Desktop.
Insert With Casts Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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