Rainieren
1 year ago

Laravel - generate unique order number

Posted 1 year ago by Rainieren

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?

Please sign in or create an account to participate in this conversation.