Laravel - generate unique order number

Laravel - generate unique order number

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Generating Unique Order Numbers in Laravel Without Race Conditions

Your seed file establishes a clear pattern: # followed by an eight-digit zero-padded number. The logic is simple arithmetic—take the highest existing index, add one, and format it. However, implementing this in a controller for live application data introduces a critical problem that seeds don't face: race conditions.

When two requests hit your create method simultaneously to generate new orders, both queries might read the same latest order number (e.g., #00000025). If both processes then increment this value and insert it, you end up with duplicate order numbers like #00000026 twice. This violates the uniqueness constraint required for valid business logic.

To solve this, you need to handle the read-modify-write cycle atomically. Laravel provides a specific pattern for this using database transactions and locking mechanisms.

The Atomic Increment Strategy

The most robust solution involves using a database transaction with row-level locking. You cannot simply query the max value in one step and insert in another; that window allows other requests to interfere. Instead, you should lock the table or the specific row holding the counter before reading it.

Assuming you have a dedicated sequence table (like order_sequence) or are using a direct counter column on your orders table, here is how you implement this safely within a controller or service class.

First, ensure you are working within a transaction block. In Laravel, this can be done using the DB::transaction() helper. Inside that block, lock the row containing the current sequence value. The SQL standard for this is SELECT ... FOR UPDATE.

use Illuminate\Support\Facades\DB;

public function create()
{
    $order = new Order;
    $order->user_id = Auth::id();

    // Start a transaction to ensure atomicity
    DB::transaction(function () {
        // Lock the row containing the next sequence number. 
        // Replace 'next_order_nr' with your actual column name or table structure.
        // This prevents other requests from reading or modifying this value until we are done.
        $sequence = DB::table('order_sequence')->where('id', 1)->lockForUpdate()->get()->first();

        // Calculate the new number based on your seed format: # + 8 digits padded
        $currentNumber = (int) $sequence->number;
        $newNumber = str_pad($currentNumber + 1, 8, '0', STR_PAD_LEFT);
        
        $order->order_nr = '#'. $newNumber;

        // Insert the new order. 
        // If you are using a separate sequence table, you must also update that row here.
        Order::create($order->toArray());

        // Update the sequence counter for the next request
        DB::table('order_sequence')->where('id', 1)->update(['number' => $currentNumber + 1]);
    });

    return view('steps.order');
}

Handling the Sequence Without a Dedicated Table

If you do not want to maintain a separate order_sequence table, you can store the counter directly in the orders table. In this scenario, you are incrementing the maximum id or a specific next_order_nr field on the orders table itself.

The logic remains identical: query the latest record with a lock, increment the value, and insert the new order. If your architecture relies solely on the orders table to track the sequence, you might look at the row with the highest order_nr numerically. However, relying on string comparison for numbers is error-prone; always cast to integers before arithmetic operations.

// Alternative: Updating a specific 'next_order' field directly in orders table
DB::transaction(function () {
    $latest = DB::table('orders')
        ->whereRaw("CAST(SUBSTRING(order_nr, 2) AS UNSIGNED) IS NOT NULL")
        ->orderByRaw("CAST(SUBSTRING(order_nr, 2) AS UNSIGNED) DESC")
        ->lockForUpdate()
        ->first();

    if ($latest) {
        $currentVal = (int) substr($latest->order_nr, 1); // Remove '#' and cast to int
        $nextVal = str_pad($currentVal + 1, 8, '0', STR_PAD_LEFT);
        
        DB::table('orders')
            ->whereRaw("CAST(SUBSTRING(order_nr, 2) AS UNSIGNED) = ?", [$currentVal])
            ->update(['order_nr' => '#' . $nextVal]); // Pre-increment to avoid duplicates
    } else {
        // Handle the case where no orders exist (start at #00000001)
        $nextVal = '00000001';
    }

    $order->order_nr = '#' . $nextVal;
});

Trade-offs and Considerations

This approach ensures that even under high concurrency, every order receives a unique number. The lockForUpdate() is the key component here. Without it, you risk duplicate generation. With it, you guarantee that only one process can hold the "write permission" for the counter at any given moment.

Performance-wise, locking a table or row adds a small overhead compared to a simple read-insert cycle. However, data integrity in financial systems or order tracking is paramount; the slight latency increase is an acceptable trade-off for correctness. If your application scales beyond a single database instance (sharding), this row-level locking strategy becomes invalid, and you would need to implement distributed locks (like Redis) or use UUIDs entirely.

For standard monolithic Laravel applications using MySQL or PostgreSQL, the transactional lock approach described above is the industry-standard solution for generating sequential, zero-padded identifiers safely.

Our network