2

A few weeks back I had an interesting inquiry regarding the handling/processing of an inventory/payment system and I've decided to implement the method of the accepted answer being it was both the most simplistic and more likely the most efficient solution given.

I'm using Laravel's Eloquent ORM in conjunction with the Slim Framework, and I'd like to perform a MYSQL transaction with a specific query regarding the decrementation of the stock of items within an inventory system. The code that I'd like to use a transaction for is the following:

    // decrement each items stock following successful payment
    try {
      // here is where i'd like to perform a transaction, rather than simple eloquent query
         foreach ($this->c->basket->all() as $product) {
            $product->decrement('stock', $product->quantity);
        }
    } catch (Exception $e) {

        // if error is caused during decremention of item(s),
        // handle accordingly 

    }

Now being that I am using Slim as aforementioned, I believe I don't have native access to the Laravel DB Facade which to my knowledge handles transactions.

Suggestions?

SIDE-NOTE

My DB Connection is set globally in an initialization file like so:

$capsule = new Illuminate\Database\Capsule\Manager();

$capsule->addConnection($container['settings']['db']);

$capsule->setAsGlobal();

$capsule->bootEloquent();
Jared Garcia
  • 751
  • 1
  • 8
  • 17

1 Answers1

0

You could get the Capsule object from the slim container and then just use the Connection object to start and commit a database transaction. If an exception occurs you just need to call the rollBack() method.

Pseudo code:

$capsule = new \Illuminate\Database\Capsule\Manager();

// Get a registered connection instance.
$connection = $capsule->getConnection();

// begin a transaction manually
$connection->beginTransaction();

try {
    // do something...
    $product->decrement('stock', $product->quantity);

    // commit a transaction via the commit method
    $connection->commit();
} catch (Exception $e) {
    // you can rollback the transaction via the rollBack method
    $connection->rollBack();
}
odan
  • 4,757
  • 5
  • 20
  • 49
  • So assuming I can execute the above logic within the `try` block of a `try catch` statement, in the `catch` block, how do I grab any exceptions from the transaction? – Jared Garcia Jan 30 '18 at 08:07