-
-
Save sineld/1e8e74fdba43efca1bb1c17ffc217b23 to your computer and use it in GitHub Desktop.
Transaction with PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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