DEV Community

Morcos Gad
Morcos Gad

Posted on

Database Transactions - Laravel

I found this wonderful article https://fideloper.com/laravel-database transactions that talks about Transactions and its importance in dealing with databases when entering or modifying more than one data in more than one table so that we can be confident that all the values ​​in the table are entered correctly, so I hope it will be useful to you in your next projects.

  • without Transactions
// Create Account
$newAcct = Account::create([
    'accountname' => Input::get('accountname'),
]);

// Create User
$newUser = User::create([
    'username' => Input::get('username'),
    'account_id' => $newAcct->id,
]);
Enter fullscreen mode Exit fullscreen mode
  • Our Transactional Toolset
// Start transaction
beginTransaction();

// Run Queries
$acct = createAccount();
$user = createUser();

// If there's an error
//    or queries don't do their job,
//    rollback!
if( !$acct || !$user )
{
    rollbackTransaction();
} else {
    // Else commit the queries
    commitTransaction();
}
Enter fullscreen mode Exit fullscreen mode
  • Basic Transactions
DB::transaction(function()
{
    $newAcct = Account::create([
        'accountname' => Input::get('accountname')
    ]);

    $newUser = User::create([
        'username' => Input::get('username'),
        'account_id' => $newAcct->id,
    ]);

    if( !$newUser )
    {
        throw new \Exception('User not created for account');
    }
});
Enter fullscreen mode Exit fullscreen mode
  • Advanced Transactions
// Start transaction!
DB::beginTransaction();

try {
    // Validate, then create if valid
    $newAcct = Account::create( ['accountname' => Input::get('accountname')] );
} catch(ValidationException $e)
{
    // Rollback and then redirect
    // back to form with errors
    DB::rollback();
    return Redirect::to('/form')
        ->withErrors( $e->getErrors() )
        ->withInput();
} catch(\Exception $e)
{
    DB::rollback();
    throw $e;
}

try {
    // Validate, then create if valid
    $newUser = User::create([
        'username' => Input::get('username'),
        'account_id' => $newAcct->id
    ]);
} catch(ValidationException $e)
{
    // Rollback and then redirect
    // back to form with errors
    DB::rollback();
    return Redirect::to('/form')
        ->withErrors( $e->getErrors() )
        ->withInput();
} catch(\Exception $e)
{
    DB::rollback();
    throw $e;
}

// If we reach here, then
// data is valid and working.
// Commit the queries!
DB::commit();
Enter fullscreen mode Exit fullscreen mode

Image description

I tried to present some basic points, but to go deeper, visit the source.
I hope you enjoyed with me and I adore you who search for everything new.

Discussion (0)