@JarekTkaczyk Yes , but i have written a function which includes transaction and i want to perform some operation on the bassis of the transaction returns it can be true / false.
for ex.
public function Test($data){
DB::transaction(function ($data) use ($data) {
try{
// Do something
}catch(Exception $e){
// Handle Exception
}
});
}
$abc=$oMasterRoles->Test($data);
so in this case how do i will get value for $abc i need it to perform some operation on this value of $abc.
@JarekTkaczyk Cool. But assume I'm doing the transaction in my route file where I not necessarily calling a function, in that case how do I determine the status?
If you use DB::beginTransaction() you can get the transaction level with this:
DB::transactionLevel()
If you are inside any transactions, you will receive the number you are in.
Ex:
DB::beginTransaction()
DB::beginTransaction()
DB::transactionLevel() // will return 2
DB::commit() // doesn't commit
DB::transactionLevel() // will return 1
DB::commit() // finally, it commits to the database
DB::transactionLevel() // will return 0
I came her for a solution for my tests and got it working with the following code:
use Illuminate\Database\Events\TransactionCommitted;
public function test_function_is_ran_with_transactions(): void
{
// Arrange
$fake = Event::fake(TransactionCommitted::class);
DB::setEventDispatcher($fake);
$model = Database\Factories\ModelFactory::new()->create();
// Act
(new App\TransactionStub)->updateThroughTransaction($model);
// Assert
Event::assertDispatched(TransactionCommitted::class);
}
Also keep in mind that the RefreshDatabase and LazilyRefreshDatabase trait also works with transactions, which can destroy your other tests.
I added a function in our abstract TestCase to allow single tests to forcibly refresh the database after the test has run;
/**
* Sometimes transactions are used, the refresh database trait should be reset after the test
*/
public function usesTransactions(): void
{
$this->beforeApplicationDestroyed(function () {
RefreshDatabaseState::$lazilyRefreshed = false;
RefreshDatabaseState::$migrated = false;
});
}