Monday, March 13, 2017

Transaction doesn't work when instantiating eloquant from a class

I try to use transactions OUTSIDE laravel. it works when I include the db instantiation right in my index file as is:

use Illuminate\Database\Capsule\Manager as Db;



$db = new Db;

$db->addConnection( [
    'driver'    => Settings::DATABASE_DRIVER,
    'host'      => Settings::DATABASE_HOST,
    'database'  => Settings::DATABASE_NAME,
    'username'  => Settings::DATABASE_USERNAME,
    'password'  => Settings::DATABASE_PASSWORD,
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => ''
] );

# Make this Capsule instance available globally via static methods... (optional)
$db->setAsGlobal();

I can then elsewhere use code like this:

Db::connection()->beginTransaction();

# Create blog post in the database and return its id
$blogPostRecordId = ( new BlogDbModel() )->create( $_POST );
Db::connection()-> rollBack();

it will correctly work and rollback back.

However, If I get an instance of the db from a class, it won't work:

class DbSql
{

    /**
     * Use the eloquent query builder and orm. Bypass PDO interface.
     * @return Capsule
     */
    public function db()
    {
        $capsule = new Capsule;

        $capsule->addConnection( [
            'driver'    => Settings::DATABASE_DRIVER,
            'host'      => Settings::DATABASE_HOST,
            'database'  => Settings::DATABASE_NAME,
            'username'  => Settings::DATABASE_USERNAME,
            'password'  => Settings::DATABASE_PASSWORD,
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => ''
        ] );

        # Make this Capsule instance available globally via static methods... (optional)
        $capsule->setAsGlobal();

        // Setup the Eloquent ORM... (optional; unless you've used setEventDispatcher())
        //$capsule->bootEloquent();


        return $capsule;
    }
}

and then use

( new DbSql() )->db()->getConnection()->beginTransaction();

# Create blog post in the database and return its id
$blogPostRecordId = ( new BlogDbModel() )->create( $_POST );
( new DbSql() )->db()->getConnection()->rollBack();

it simply won't work and the transaction is ignored. Why does getting the db instance from a class instantiation make the process fail ? I would prefer to use an instance as needed.



via Robert Brax

Advertisement