DEV Community

Morcos Gad
Morcos Gad

Posted on

3 1

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.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay