Skip to content

Instantly share code, notes, and snippets.

@ju5t
Forked from Patabugen/Transaction.php
Created June 29, 2022 14:38
Show Gist options
  • Save ju5t/72fa0ff08f34bf73957851d708154fb6 to your computer and use it in GitHub Desktop.
Save ju5t/72fa0ff08f34bf73957851d708154fb6 to your computer and use it in GitHub Desktop.
Eloquent Model event hook to allow inserting primary keys into SQL Server tables with IDENTITY_INSERT = off
<?php
trait PrimaryKey
{
protected $primaryKey = 'TransactionID';
public static function bootPrimaryKey()
{
static::creating(function(self $model) {
$pkColumn = $model->primaryKey;
$tableName = $model->table;
if (empty($model->$pkColumn)) {
$lastPk = $model->getQuery()->max($pkColumn);
$model->$pkColumn = $lastPk + 1;
}
$model->getConnection()->beforeExecuting(function($query, $bindings, \Illuminate\Database\Connection $connection) use ($tableName) {
// Perform some rudimentary escaping. SQL Server allows any character in the table name
// so we will remove characters SQL Server uses to wrap the table name and wrap
// it ourselves.
$tableName = str_replace(['[', ']', '`'], '', $tableName);
$connection->getPdo()->exec('SET IDENTITY_INSERT ['.$tableName.'] ON;');
$connection->commit();
});
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment