1

I am making a Laravel 5.7 system which has tons of code and models, but the ones in problem are:

  • Order - first created
  • Transport (1:1 Order) - afterwards created for Order

So Order.php has a function as follows:

public function create_transport(){
 ...
 // Create transport for order
 $transport = Transport::create([
 'order_id' => $this->id,
 'user_id' => $this->user_id,
 'printed' => 0,
 'sent' => 0,
 'commission_id' => $commission->id,
 ]);
 ...
}

Now this function is called in 5 different functions (once) overall in 3 controllers like this:

if( ... && !$order->transport ){
 $order->create_transport();
}

As you can see this should create a Transport only if no transport exists for an order.

However, in our production system we have confirmed 3 cases of duplicate Transport created in last year. The duplicates are exactly same except ID, also same created_at timestamp. Any ideas?

asked May 14, 2022 at 20:04
1
  • 1
    no ideas but I'm having a similar problem. First noticed in Laravel 5.5 & PHP 7.1, still occuring after update to Laravel 8 and PHP 8.1 Commented Aug 4, 2022 at 16:22

1 Answer 1

0

so answer or update for this.

The reason was actually the Race Condition. There was a double click action performed on the button, which only happened sometimes as well because of the speed of clicking.

The way I handled it in this project is using DB::transaction()

public function create_transport(){
 DB::transaction(function() {
 $transport = $this->transport()->sharedLock()->first();
 ... here was validation if transport exists ...
 // Create transport for order
 $transport = Transport::create([
 'order_id' => $this->id,
 'user_id' => $this->user_id,
 'printed' => 0,
 'sent' => 0,
 'commission_id' => $commission->id,
 ]);
 ...
 }, 5);
}
answered Jan 9, 2023 at 15:43
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.