Balthild Ires
Balthild Ires

Reputation: 41

How to use transaction in Eloquent Model

I use Capsule to manage database connections in my project, and use Model to operate databases, like this:

// Init Eloquent ORM Connection
$capsule = new Capsule;
$capsule->addConnection(Config::getDbConfig());
$capsule->addConnection(Config::getRadiusDbConfig(), 'radius');
$capsule->bootEloquent();

I want to use transaction while executing a large modification to database, but there're no related methods in the class Model.

Because of the Capsule, I'm not able to use Illuminate\Suooprt\Facades\DB , since it reports this error:

PHP Fatal error:  Uncaught RuntimeException: A facade root has not been set. in
E:\Projects\ss-panel\vendor\illuminate\support\Facades\Facade.php:210

How should I deal with it?

Upvotes: 1

Views: 3742

Answers (1)

Malvin Lok
Malvin Lok

Reputation: 642

I am using Eloquent ORM outside Laravel.

Here is the solution how I start transaction.

You can add an base model extend \Illuminate\Database\Eloquent\Model.

<?php

use Illuminate\Database\Eloquent\Model as EloquentModel;

class Model extends EloquentModel
{
     public static function beginTransaction()
     {
          self::getConnectionResolver()->connection()->beginTransaction();
     }

     public static function commit()
     {
         self::getConnectionResolver()->connection()->commit();
     }

     public static function rollBack()
     {
         self::getConnectionResolver()->connection()->rollBack();
     }    
}

Then, you can use it like this:

Model::beginTransaction();

//do what you like.

Model::commit();

// OR

Model::rollBack();

Upvotes: 8

Related Questions