Skip to content

Instantly share code, notes, and snippets.

@sineld
Last active December 29, 2022 16:54
Show Gist options
  • Save sineld/1e8e74fdba43efca1bb1c17ffc217b23 to your computer and use it in GitHub Desktop.
Save sineld/1e8e74fdba43efca1bb1c17ffc217b23 to your computer and use it in GitHub Desktop.
Transaction with PHP
<?php
use Illuminate\Support\Facades\DB;
DB::beginTransaction();
try {
DB::insert(...);
DB::insert(...);
DB::insert(...);
DB::commit(); //bunu yapmazsan db ye insert işlemerini geçirmiyor
// all good
} catch (\Exception $e) {
DB::rollback(); //bir Exception olduğunda Exception a kadar olan işlemleri yapmaz böyle dediğimizde
// something went wrong
}
// or a complex version:
$user = DB::transaction(function() use ($updateData, $teamIds) {
// Burada bir hata meydana gelirse exception fırlatacak
$user->update($updateData);
// Burada bir hata meydana gelirse üstteki update işlemi
// geri alınacak ve exception fırlatacak.
$user->teams
->sync($teamIds);
return $user;
});
UserUpdated::dispatch($user);
# Database Transactions
# You may use the transaction method provided by the DB facade to run a set of operations within a database transaction. If an exception is thrown within the transaction closure, the transaction will automatically be rolled back and the exception is re-thrown. If the closure executes successfully, the transaction will automatically be committed. You don't need to worry about manually rolling back or committing while using the transaction method:
DB::transaction(function () {
DB::update('update users set votes = 1');
DB::delete('delete from posts');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment