Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Rainieren's avatar

Laravel - generate unique order number

Hello, I'm currently trying to generate a unique order number when the user reaches the create method. The order numbers are generated like this in the seed and need to look like this as well

Seed

foreach(range(1,25) as $index)
        {
            DB::table('orders')->insert([

                'user_id' => rand(1,25),
                'order_nr' => '#' . sprintf("%08d", $index),
                'price_sum' => $faker->randomNumber($nbDigits = 4, $strict = false) . '.' . $faker->randomNumber($nbDigits = 2, $strict = false),
                'status' => $faker->randomElement(['paid', 'pending', 'failed']),
                'created_at' => Carbon::now(),
                'updated_at' => Carbon::now(),

            ]);
        }

The order numbers look like this #00000001 or #00000002. Now when the user reaches the create method in my controller a new unique order number in this sequence needs to be created. How can I achieve that? The controller currently looks like this:

 public function create()
    {
        $order = new Order;

        $order->user_id = Auth()->id();
        $order->order_nr = 


        dd($order);


        return view('steps.order');
    }

It needs to check the latest order number and create one with +1 on that order number. Say for instance there are 25 orders and the last one is #00000025 the one that needs to be created next needs to be #00000026. How can I achieve that?

0 likes
6 replies
biishmar's avatar

@Rainieren

  • Are you sure you want to create unique order number in incremental value, i dont see anything unique here, just same as primary key.
  • If i were you i would create alpha-numerical for unique order number.
anilkumarthakur60's avatar

you can concatenate user_id and current date time which will always be unique order_id

Watsica's avatar

I'm using Eloquent, and I have a field distinct from the id column that needs to be unique. It can be numeric or alphanumeric. How would I generate this?

My first thought was to make it equal to the id column since that is guaranteed to be unique. But since this column is not-null (NN), and apparently the id doesn't generate until after $newItem->save();, I'm unable to do so.

Thoughts?

martinbean's avatar

@watsica We can’t make up an algorithm for you. You need to decide on the format of your order numbers and then write the code to achieve that.

Please or to participate in this conversation.