Database Transactions in Laravel: 5 Open-Source Examples

Database Transactions are essential if you want to perform a few DB insert/update/delete operations and ensure the integrity of the data. Let's take a look at 5 different examples from Laravel open-source projects.


1. themsaid/ergodnc: Create Office with Tags

The code of the Controller:

1class OfficeController extends Controller
2{
3 public function create(): JsonResource
4 {
5 $attributes = (new OfficeValidator())->validate(
6 $office = new Office(),
7 request()->all()
8 );
9 
10 $attributes['approval_status'] = Office::APPROVAL_PENDING;
11 $attributes['user_id'] = auth()->id();
12 
13 $office = DB::transaction(function () use ($office, $attributes) {
14 $office->fill(
15 Arr::except($attributes, ['tags'])
16 )->save();
17 
18 if (isset($attributes['tags'])) {
19 $office->tags()->attach($attributes['tags']);
20 }
21 
22 return $office;
23 });
24 
25 // ...
26 }
27}

As you can see, the Office model new record is created, and then, with the many-to-many relation ->attach() method, DB Transaction ensures that if tag attaching fails, then the Office new record is also rolled back.

See the original code on GitHub.


2. JuanDMeGon/Laravel-from-Scratch: Many-To-Many with Deadlocks

The code of the Controller:

1class OrderController extends Controller
2{
3 public function store(Request $request)
4 {
5 return DB::transaction(function() use($request) {
6 $user = $request->user();
7 
8 $order = $user->orders()->create([
9 'status' => 'pending',
10 ]);
11 
12 $cart = $this->cartService->getFromCookie();
13 
14 $cartProductsWithQuantity = $cart
15 ->products
16 ->mapWithKeys(function ($product) {
17 $quantity = $product->pivot->quantity;
18 
19 if ($product->stock < $quantity) {
20 throw ValidationException::withMessages([
21 'cart' => "There is not enough stock for the quantity you required of {$product->title}",
22 ]);
23 }
24 
25 $product->decrement('stock', $quantity);
26 $element[$product->id] = ['quantity' => $quantity];
27 
28 return $element;
29 });
30 
31 $order->products()->attach($cartProductsWithQuantity->toArray());
32 
33 return redirect()->route('orders.payments.create', ['order' => $order->id]);
34 }, 5);
35 }
36}

Let's discuss what transaction is happening here, and why.

  • We create the Order
  • Then we decrement the stock of $product
  • Finally, we attach Products to the $order

Interesting thing here: did you know you can add a number parameter to the DB::transaction() method?

See above:

1DB::transaction(function() use($request) {
2 // ... whatever is inside
3}, 5);

What does that 5 do?

Quote from the original Laravel docs:

The transaction method accepts an optional second argument which defines the number of times a transaction should be retried when a deadlock occurs. Once these attempts have been exhausted, an exception will be thrown.

See the original code on GitHub.


3. amitavroy/doctor-app

The code of the Service class:

1class PatientService
2{
3 public function createPatient($patientData): Patient
4 {
5 $settingService = app()->make(SettingService::class);
6 
7 try {
8 DB::beginTransaction();
9 $patientNumber = $settingService->getNextPatientNumber();
10 
11 $patient = Patient::create([
12 'patient_id' => now()->format('Ym') . $patientNumber,
13 'name' => $patientData['name'],
14 'phone_number' => $patientData['phone_number'],
15 'year_of_birth' => now()->subYears($patientData['age'])->format('Y'),
16 'weight' => $patientData['weight'],
17 ]);
18 
19 $settingService->incrementLastPatientNumber();
20 DB::commit();
21 
22 return $patient;
23 } catch (Exception $exception) {
24 logger()->error($exception->getMessage());
25 }
26 }
27}

This one is interesting: it uses beginTransaction() and commit() manually, and also wraps the transaction in a try .. catch statement, additionally.

See the original code on GitHub.


4. pixelfed/pixelfed: Delete Everything Safely

The code of the Job class:

1class DeleteRemoteProfilePipeline implements ShouldQueue
2{
3 // ...
4 
5 public function handle()
6 {
7 $profile = $this->profile;
8 
9 DB::transaction(function() use ($profile) {
10 $profile->avatar->forceDelete();
11 
12 $id = $profile->id;
13 
14 MediaTag::whereProfileId($id)->delete();
15 StatusHashtag::whereProfileId($id)->delete();
16 DirectMessage::whereFromId($id)->delete();
17 FollowRequest::whereFollowingId($id)
18 ->orWhere('follower_id', $id)
19 ->forceDelete();
20 Follower::whereProfileId($id)
21 ->orWhere('following_id', $id)
22 ->forceDelete();
23 Like::whereProfileId($id)->forceDelete();
24 });
25 }
26}

This is pretty straightforward. There are so many things related to the profile, so there's quite a big chance of failure if some of those records malfunction during the deletion process. So DB Transaction is a no-brainer here.

More things are happening in this Job, so see the original code on GitHub.


5. akaunting/akaunting

The code of a custom PHP Action class method:

1class Reconciliations extends BulkAction
2{
3 public function reconcile($request)
4 {
5 $reconciliations = $this->getSelectedRecords($request);
6 
7 foreach ($reconciliations as $reconciliation) {
8 \DB::transaction(function () use ($reconciliation) {
9 $reconciliation->reconciled = 1;
10 $reconciliation->save();
11 
12 Transaction::where('account_id', $reconciliation->account_id)
13 ->isNotReconciled()
14 ->whereBetween('paid_at', [$reconciliation->started_at, $reconciliation->ended_at])->each(function ($item) {
15 $item->reconciled = 1;
16 $item->save();
17 });
18 });
19 }
20 }
21 
22}

Reconciliation is a financial term for "merging transactional records" or something like that.

So, we need to mark the reconciliation as saved, but also need to mark individual transactions as reconciled.

Some of you would ask, why there's an ->each() function for each Transaction, instead of just a bulk update? I assume there are Observers or other events that are automatically fired on the individual record update, that would not be automatically executed otherwise.

See the original code on GitHub.


Want More Code Examples?

So, these are just 5 examples. We've collected hundreds of code examples from Laravel open-source projects.

You can take a look at a few more DB transaction examples, or browse through all the list of code examples by topic/tag.

avatar
Loganathan Natarajan

Thanks for sharing and learned new things.

👍 2
avatar

Informative

Like our articles?

Become a Premium Member for $129/year or $29/month

Recent Premium Tutorials