Answers for "using transactions in laravel"

PHP
10

laravel transactions

DB::beginTransaction();

try {
    DB::insert(...);
    DB::insert(...);
    DB::insert(...);

    DB::commit();
    // all good
} catch (\Exception $e) {
    DB::rollback();
    // something went wrong
}
Posted by: Guest on May-19-2020
0

laravel transaction

// 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();
Posted by: Guest on January-17-2022

Code answers related to "using transactions in laravel"

Browse Popular Code Answers by Language