DB::transaction()の実装は、ManagesTransactionsというtraitで実装されているようだ。
実装を見てみると、一つ目の引数で指定しているコールバック関数の返り値をそのまま返していることが分かる。
public function transaction(Closure $callback, $attempts = 1) { for ($currentAttempt = 1; $currentAttempt <= $attempts; $currentAttempt++) { $this->beginTransaction(); // We'll simply execute the given callback within a try / catch block and if we // catch any exception we can rollback this transaction so that none of this // gets actually persisted to a database or stored in a permanent fashion. try { $callbackResult = $callback($this); } // If we catch an exception we'll rollback this transaction and try again if we // are not out of attempts. If we are out of attempts we will just throw the // exception back out and let the developer handle an uncaught exceptions. catch (Throwable $e) { $this->handleTransactionException( $e, $currentAttempt, $attempts ); continue; } try { if ($this->transactions == 1) { $this->getPdo()->commit(); } $this->transactions = max(0, $this->transactions - 1); if ($this->transactions == 0) { optional($this->transactionsManager)->commit($this->getName()); } } catch (Throwable $e) { $this->handleCommitTransactionException( $e, $currentAttempt, $attempts ); continue; } $this->fireConnectionEvent('committed'); return $callbackResult; } }
ということで、こんな感じに書いてあげると、
DB保存したデータのオブジェクトを返り値として取得することができる。
$data = DB::transaction(function () { $data = new Data(); $data->value = 'hoge'; $data->save(); return $data; });