'Model create() method is executed twice SOMETIMES and creates duplicated entry for 1:1 relation

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?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source