Created
May 14, 2014 14:06
-
-
Save rutoru/72b06387b6b3601eed1d to your computer and use it in GitHub Desktop.
How to use transaction with Laravel's Eloquent ORM and the Slim Framework
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Illuminate DB Class | |
* | |
* @author rutoru | |
* @package Runa-CCA | |
* @license http://www.opensource.org/licenses/mit-license.php 2014 rutoru | |
*/ | |
namespace Runa_CCA\Model; | |
class IlluminateDB{ | |
/** | |
* Object Variables | |
*/ | |
private $capsule; | |
/** | |
* Constructor | |
* | |
*/ | |
public function __construct(){ | |
$this->capsule = new \Illuminate\Database\Capsule\Manager(); | |
$this->capsule->addConnection(Self::getIlluminateSettings()); | |
// Set the event dispatcher used by Eloquent models... (optional) | |
$this->capsule->setEventDispatcher(new \Illuminate\Events\Dispatcher( | |
new \Illuminate\Container\Container() | |
) | |
); | |
// Set the cache manager instance used by connections... (optional) | |
//$this->capsule->setCacheManager(...); | |
// Make this Capsule instance available globally via static methods... (optional) | |
$this->capsule->setAsGlobal(); | |
// Setup the Eloquent ORM... (optional; unless you've used setEventDispatcher()) | |
$this->capsule->bootEloquent(); | |
} | |
/** | |
* Illuminate Connection and Bootup | |
* | |
* @return \Illuminate\Database\Connection Illuminate Connection Object | |
*/ | |
public function getIlluminateConnection(){ | |
return $this->capsule->getConnection(); | |
} | |
/** | |
* getIlluminateSettings | |
* | |
* @return String[] Connection information | |
*/ | |
static function getIlluminateSettings(){ | |
return [ | |
'driver' => 'mysql', | |
'host' => 'localhost', | |
'database' => '', | |
'username' => '', | |
'password' => '', | |
'charset' => 'utf8', | |
'collation' => 'utf8_unicode_ci', | |
'prefix' => '', | |
]; | |
} | |
} |
then where is the sample query to use.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can see "How to use Laravel's Eloquent ORM with the Slim Framework" on the Slim website.
I made a class named "IlluminateDB" in order to use _transaction_.
When you use the class, first, you need to make \Illuminate\Database\Capsule\Manager object and get the DB connection from the object. The method "getConnection()" returns the connection. In this example, IlluminateDB object method "getIlluminateConnection()" returns the object. Then, call "getPdo()->beginTransaction()" method. It starts transaction. Finally, If you want to commit, call "getPdo()->commit()", or if you want to rollback call "getPdo()->rollback()".
See a sample script below:
cf.) https://github.com/rutoru/Runa-CCA