This is in the context of using eloquent OUTSIDE laravel. It has also simplified, explicit code. The gloal is to jave working transactions.
Database initialisation code:
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;
}
}
Here is simplified version of a controller with the transaction codes. Note that it explicitly tries to rollback:
class PostController extends BaseController
{
public function post( Request $request, Response $response )
{
( new DbSql() )->db()->getConnection()->beginTransaction();
# Create name categories if necessary, and return their ids
$womenNamesIds = ( new ModelNamesDbModel() )->createModelNamesCategories( $_POST );
# Create blog post in the database and return its id
$blogPostRecordId = ( new BlogDbModel() )->create( $_POST );
( new DbSql() )->db()->getConnection()->rollBack();
return;
}
}
And here is a model code called by the controller:
class BlogDbModel
{
public function create( array $blogPost ): int
{
# Inserts record and gets its db id.
$recordId = ( new DbSql )->db()->table( 'blog_posts' )->insertGetId(
[ 'blog_title' => $blogPost[ 'blog_title' ] ]
);
return $recordId;
}
}
Note that I need the transaction handled in the controller, as there are more model operations and the central point of control is the controller.
So the code above does nothing, the blog post gets created even if there is no commit instruction, and instead an explicit rollback.
Questions:
- Should I enable bootEloquent(); ? (it doesn't work anyway with it enabled in this state)
- Could it be because I need to have the same db instance used by controller transactions and model ?
- What should I do to have the transactions working ?
via Robert Brax