Skip to content

Instantly share code, notes, and snippets.

@IsraelOrtuno
Created February 3, 2016 11:58
Show Gist options
  • Save IsraelOrtuno/308f3259daaec3515292 to your computer and use it in GitHub Desktop.
Save IsraelOrtuno/308f3259daaec3515292 to your computer and use it in GitHub Desktop.
<?php
namespace Devio\Propertier;
use Throwable;
trait SavesUsingTransaction
{
protected $savingTransaction = true;
public function save(array $options = [])
{
if ($this->savingTransaction) {
return $this->saveWithinTransaction($options);
}
return parent::save($options);
}
public function saveWithinTransaction(array $options = [])
{
$connection = $this->getConnection();
$connection->beginTransaction();
try {
if ($saved = parent::save($options)) {
$connection->commit();
} else {
$connection->rollBack();
}
return $saved;
} catch (Throwable $e) {
$connection->rollBack();
throw $e;
}
}
public function savingTransaction($value)
{
$this->savingTransaction = $value;
}
public function disableSavingTransaction()
{
$this->savingTransaction = false;
}
public function enableSavingTransaction()
{
$this->savingTransaction = true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment