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

melx's avatar
Level 4

Avoid Duplication

Hello ,

How can i avoid duplication here?

            $tgl = Carbon::now()->format('Y-m-d');
                $no = DB::select("SELECT max(right(bill_number,4)) as bill_no from sales WHERE date(updated_at)='$tgl'");
                foreach ($no as $idnx) {
                    $noo = (int) $idnx->bill_no;
                }

                $tambah = $noo + 1;

                if ($tambah < 10) {
                    $bill_number = "E" . Carbon::now()->format('dmy') . "000" . $tambah;
                } else if ($tambah < 100) {
                    $bill_number = "E" . Carbon::now()->format('dmy') . "00" . $tambah;
                } else if ($tambah < 1000) {
                    $bill_number = "E" . Carbon::now()->format('dmy') . "0" . $tambah;
                } else if ($tambah < 10000) {
                    $bill_number = "E" . Carbon::now()->format('dmy') . $tambah;
                }



               if($request->filled('backdate')) {
                              $date = request('backdate');
                          } else {
                              $date = Carbon::now()->format('Y-m-d H:i:s');
                          }
              if ($request->slave_ID) {
                         foreach ($request->slave_ID as $key => $value) {
                      $data =[

                          'bill_number'       =>     $bill_number,
                          'user_id'     =>    Auth::user()->id,
                          'tag_id'      =>    Auth::user()->team_id,
                          'unit_issue_id'     =>    $request->unit_id,
                          'customer_agent'      =>    $request->customer_agent,
                          'payment_method'      =>    $request->payment_method,
                          'borderName'      =>    $request->borderName,
                          'tag_area'      =>    $request->tag_area,
                          'cargo_type'      =>    $request->cargo_type,
                          'chasisNo'      =>    $request->chasisNo,
                          'ITNo'      =>    $request->ITNo,
                          'driverName'      =>    $request->driverName,
                          'License'     =>    $request->License,
                          'driverPhone'     =>    $request->driverPhone,
                          'subT1'     =>    $request->subT1,
                          'TruckNo'     =>    $request->TruckNo,
                          'TrailerNo'     =>    $request->trailerNo,
                          'container_no'      =>    $request->containerNo,
                          'comments'      =>    $request->comment,
                          'amount'      =>    $request->amount,
                          'discount'      =>    $request->discount,
                          'sale_type'     =>    $request->sale_type,
                          'currency'      =>    $request->currency,
                           'created_at'=>$date,
                           'slave_id'=>$request->slave_ID[$key],
                            
                        ];


                 

                             Sales::create($data); 
              }

              }else{


                        $data2 =[

                          'bill_number'       =>     $bill_number,
                          'user_id'     =>    Auth::user()->id,
                          'tag_id'      =>    Auth::user()->team_id,
                          'unit_issue_id'     =>    $request->unit_id,
                          'customer_agent'      =>    $request->customer_agent,
                          'payment_method'      =>    $request->payment_method,
                          'borderName'      =>    $request->borderName,
                          'tag_area'      =>    $request->tag_area,
                          'cargo_type'      =>    $request->cargo_type,
                          'chasisNo'      =>    $request->chasisNo,
                          'ITNo'      =>    $request->ITNo,
                          'driverName'      =>    $request->driverName,
                          'License'     =>    $request->License,
                          'driverPhone'     =>    $request->driverPhone,
                          'subT1'     =>    $request->subT1,
                          'TruckNo'     =>    $request->TruckNo,
                          'TrailerNo'     =>    $request->trailerNo,
                          'container_no'      =>    $request->containerNo,
                          'comments'      =>    $request->comment,
                          'amount'      =>    $request->amount,
                          'discount'      =>    $request->discount,
                          'sale_type'     =>    $request->sale_type,
                          'currency'      =>    $request->currency,
                           'created_at'=>$date,

                          'slave_id'=> ($request->has('slave_ID') && count($request->slave_ID) > 0)? count($request->slave_ID) : null,
                        ];


                 

                             Sales::create($data2); 
              }
          return $this->print_sales_bill_cash($bill_number);
  

My code is works file to create but when i refresh the page it duplicate the data with new bil_number

0 likes
42 replies
prasadchinwal5's avatar

@emfinanga Its not clear what some of the lines do in the code example

foreach ($no as $idnx) {
	$noo = (int) $idnx->bill_no;
}

$tambah = $noo + 1;
                 		

But you can make this code more readable and reduce LOC. You can replace this

if($request->filled('backdate')) {
                              $date = request('backdate');
                          } else {
                              $date = Carbon::now()->format('Y-m-d H:i:s');
                          }

With:

$date = $request->filled('backdate') ? request('backdate') : Carbon::now()->format('Y-m-d H:i:s');

Instead of if statements here you can use switch statement:

 if ($tambah < 10) {
                    $bill_number = "E" . Carbon::now()->format('dmy') . "000" . $tambah;
                } else if ($tambah < 100) {
                    $bill_number = "E" . Carbon::now()->format('dmy') . "00" . $tambah;
                } else if ($tambah < 1000) {
                    $bill_number = "E" . Carbon::now()->format('dmy') . "0" . $tambah;
                } else if ($tambah < 10000) {
                    $bill_number = "E" . Carbon::now()->format('dmy') . $tambah;
                }
melx's avatar
Level 4

@prasadchinwal5 ,

how can i write switch there?

and how can i avoid that duplication because am using bill_number as unique

prasadchinwal5's avatar

So you can do something like this:

switch(true) {
  case $tambah < 10:
    $bill_number = "E" . Carbon::now()->format('dmy') . "000" . $tambah;
    break;
  case $tambah < 100:
    $bill_number = "E" . Carbon::now()->format('dmy') . "00" . $tambah;
    break;
  case $tambah < 1000:
    $bill_number = "E" . Carbon::now()->format('dmy') . "0" . $tambah;
    break;
  case $tambah < 10000:
    $bill_number = "E" . Carbon::now()->format('dmy') . $tambah;
    break;
  default:
    $bill_number = 'severe';
    break;
}

You can slowly start with a piece of code and try to concise it.

melx's avatar
Level 4

Oky let me try,

And how about create($data) to avoid duplicate

Can i use this bill_number as to check and updateOrCreate

Help me on this @prasadchinwal5

melx's avatar
Level 4

@prasadchinwal5

i want try like this

                    $date = $request->filled('backdate') ? request('backdate') : Carbon::now()->format('Y-m-d H:i:s');
               // if($request->filled('backdate')) {
               //                $date = request('backdate');
               //            } else {
               //                $date = Carbon::now()->format('Y-m-d H:i:s');
               //            }
              if ($request->slave_ID) {
                         foreach ($request->slave_ID as $key => $value) {
                          Sales::updateOrCreate(
                            ['bill_number'       =>     $bill_number,'customer_agent'      =>    $request->customer_agent],
                            ['tag_id'      =>    Auth::user()->team_id ],[
                         'bill_number'       =>     $bill_number,
                         'user_id'     =>    Auth::user()->id,
                          'unit_issue_id'     =>    $request->unit_id,
                          'payment_method'      =>    $request->payment_method,
                          'borderName'      =>    $request->borderName,
                          'tag_area'      =>    $request->tag_area,
                          'cargo_type'      =>    $request->cargo_type,
                          'chasisNo'      =>    $request->chasisNo,
                          'ITNo'      =>    $request->ITNo,
                          'driverName'      =>    $request->driverName,
                          'License'     =>    $request->License,
                          'driverPhone'     =>    $request->driverPhone,
                          'subT1'     =>    $request->subT1,
                          'TruckNo'     =>    $request->TruckNo,
                          'TrailerNo'     =>    $request->trailerNo,
                          'container_no'      =>    $request->containerNo,
                          'comments'      =>    $request->comment,
                          'amount'      =>    $request->amount,
                          'discount'      =>    $request->discount,
                          'sale_type'     =>    $request->sale_type,
                          'currency'      =>    $request->currency,
                           'created_at'=>$date,
                           'slave_id'=>$request->slave_ID[$key],
                            
                        ]);              // Sales::create($data); 
              }

              }else{

                Sales::updateOrCreate(
                            ['bill_number'       =>     $bill_number,'customer_agent'      =>    $request->customer_agent],
                            ['tag_id'      =>    Auth::user()->team_id ],[
                          // 'tag_id'      =>    Auth::user()->team_id,
                         

                          'unit_issue_id'     =>    $request->unit_id,
                          // 'customer_agent'      =>    $request->customer_agent,
                          'payment_method'      =>    $request->payment_method,
                          'borderName'      =>    $request->borderName,
                          'tag_area'      =>    $request->tag_area,
                          'cargo_type'      =>    $request->cargo_type,
                          'chasisNo'      =>    $request->chasisNo,
                          'ITNo'      =>    $request->ITNo,
                          'driverName'      =>    $request->driverName,
                          'License'     =>    $request->License,
                          'driverPhone'     =>    $request->driverPhone,
                          'subT1'     =>    $request->subT1,
                          'TruckNo'     =>    $request->TruckNo,
                          'TrailerNo'     =>    $request->trailerNo,
                          'container_no'      =>    $request->containerNo,
                          'comments'      =>    $request->comment,
                          'amount'      =>    $request->amount,
                          'discount'      =>    $request->discount,
                          'sale_type'     =>    $request->sale_type,
                          'currency'      =>    $request->currency,
                           'created_at'=>$date,

                          'slave_id'=> ($request->has('slave_ID') && count($request->slave_ID) > 0)? count($request->slave_ID) : null,
                        ]);


                 

                             // Sales::create($data2); 
              }

am get this error

             Trying to get property 'bill_number' of non-object
prasadchinwal5's avatar

Hey @emfinanga As the error says the variable $bill_number is not defined or getting set. Can you share the code where you set the variable $bill_number ?

melx's avatar
Level 4

Am using switch

switch(true) { case $tambah < 10: $bill_number = "E" . Carbon::now()->format('dmy') . "000" . $tambah; break; case $tambah < 100: $bill_number = "E" . Carbon::now()->format('dmy') . "00" . $tambah; break; case $tambah < 1000: $bill_number = "E" . Carbon::now()->format('dmy') . "0" . $tambah; break; case $tambah < 10000: $bill_number = "E" . Carbon::now()->format('dmy') . $tambah; break; default: $bill_number = 'severe'; break; }

automica's avatar

@prasadchinwal5 even better extract to a private method

private function getBillNumber($tambah)
{
	switch(true) {
	  case $tambah < 10:
	   return "E" . Carbon::now()->format('dmy') . "000" . $tambah;
	  case $tambah < 100:
	    return "E" . Carbon::now()->format('dmy') . "00" . $tambah;

	  case $tambah < 1000:
	    return "E" . Carbon::now()->format('dmy') . "0" . $tambah;
	  case $tambah < 10000:
	    return "E" . Carbon::now()->format('dmy') . $tambah;
	  default:
	    return 'severe';
	}
}
1 like
melx's avatar
Level 4

Oky thanks and how can i use in public function?

Do you think can not duplicate

Tray2's avatar

A simple solution would be to always assign the common stuff then the parts that differs with slight duplication.

Something like

  $tgl = Carbon::now()->format('Y-m-d');
      $no = DB::select("SELECT max(right(bill_number,4)) as bill_no from sales WHERE date(updated_at)='$tgl'");
      foreach ($no as $idnx) {
          $noo = (int) $idnx->bill_no;
      }

      $tambah = $noo + 1;

      if ($tambah < 10) {
          $bill_number = "E" . Carbon::now()->format('dmy') . "000" . $tambah;
      } else if ($tambah < 100) {
          $bill_number = "E" . Carbon::now()->format('dmy') . "00" . $tambah;
      } else if ($tambah < 1000) {
          $bill_number = "E" . Carbon::now()->format('dmy') . "0" . $tambah;
      } else if ($tambah < 10000) {
          $bill_number = "E" . Carbon::now()->format('dmy') . $tambah;
      }

      $data =[

          'bill_number'       =>     $bill_number,
          'user_id'     =>    Auth::user()->id,
          'tag_id'      =>    Auth::user()->team_id,
          'unit_issue_id'     =>    $request->unit_id,
          'customer_agent'      =>    $request->customer_agent,
          'payment_method'      =>    $request->payment_method,
          'borderName'      =>    $request->borderName,
          'tag_area'      =>    $request->tag_area,
          'cargo_type'      =>    $request->cargo_type,
          'chasisNo'      =>    $request->chasisNo,
          'ITNo'      =>    $request->ITNo,
          'driverName'      =>    $request->driverName,
          'License'     =>    $request->License,
          'driverPhone'     =>    $request->driverPhone,
          'subT1'     =>    $request->subT1,
          'TruckNo'     =>    $request->TruckNo,
          'TrailerNo'     =>    $request->trailerNo,
          'container_no'      =>    $request->containerNo,
          'comments'      =>    $request->comment,
          'amount'      =>    $request->amount,
          'discount'      =>    $request->discount,
          'sale_type'     =>    $request->sale_type,
          'currency'      =>    $request->currency,
          'created_at'=>$date,
        ];


      if($request->filled('backdate')) {
                    $date = request('backdate');
                } else {
                    $date = Carbon::now()->format('Y-m-d H:i:s');
                }
    if ($request->slave_ID) {
      foreach ($request->slave_ID as $key => $value) {
        $data['slave_id'] =$request->slave_ID[$key],
        Sales::create($data); 
      }

    }else{
      $data['slave_id'] = ($request->has('slave_ID') && count($request->slave_ID) > 0)? count($request->slave_ID) : null;
      Sales::create($data); 
    }
return $this->print_sales_bill_cash($bill_number);
melx's avatar
Level 4

@tray2, this $data or $date ?

Check this line

    $date['slave_id'] =$request->slave_ID[$key],
    Sales::create($data);
Tray2's avatar

It should be $data I updated my reply.

Tray2's avatar

There was another type-o in the else statement it said

Sales::create($data2);

It should be

Sales::create($data);
melx's avatar
Level 4

@tray2 i tested it still duplicate,

the problem here is bill_number after save the data, when i refresh the page, its takes the same and save as new data with new bill_number

I think that the billnumber is create as new because it check the last and create new one as the same data

Tray2's avatar

Ah duplicates in the database I thought it was duplicate code.

Anyway my code made it cleaner :)

So what you want to do is pad the bill_number.

E210120210001
E210120210099
E210120210999
E210120211001
E210120211002

You can use str_pad for that

$bill_number = 'E' . Carbon::now()->format('dmy') . str_pad($tambah, 4, '0', STR_PAD_LEFT);

Instead of using the if statement.

This is probalby the issue

 $no = DB::select("SELECT max(right(bill_number,4)) as bill_no from sales WHERE date(updated_at)='$tgl'");

It will select the higest value in the last four characters in the bill_no. and nothing else.

So if its 0099 that is the highest it will fetch that.

So there is no need to loop over it.

Something like this

 $no = DB::select("SELECT max(right(bill_number,4)) as bill_no from sales WHERE date(updated_at)='$tgl'");
      
 $noo = (int) $no->bill_no +1;
melx's avatar
Level 4

ok @tray2 , so the code will be like this?

           $no = DB::select("SELECT max(right(bill_number,4)) as bill_no from sales WHERE date(updated_at)='$tgl'");
            foreach ($no as $idnx) {
                $noo = (int) $idnx->bill_no;
            }

            $tambah = $noo + 1;
    $bill_number = 'E' . Carbon::now()->format('dmy') . str_pad($tambah, 4, '0', STR_PAD_LEFT);
melx's avatar
Level 4

my request is created well with this code good

    array:22 [▼
          "_token" => "eMicRSunxukf6D5as37h43Impw4mwNqBFF76Ls7D"
          "unit_id" => "6"
          "sale_type" => "1"
          "backdate" => null
          "customer_agent" => "ABCG"
          "payment_method" => "1"
          "currency" => "1"
          "amount" => "70"
          "discount" => "7"
          "tag_area" => "DEPOT DALBIT"
          "borderName" => "1"
          "cargo_type" => "2"
          "TruckNo" => "T678 TTY"
          "trailerNo" => "T 566 ABD"
          "chasisNo" => null
          "ITNo" => null
          "container_no" => "TTGHBRT6564"
          "driverName" => "FEKRR"
          "License" => "4000231136"
          "driverPhone" => "0754262956"
          "subT1" => "TZS466676767"
          "comment" => "OK"
          ]

when i refresh the page the same data is created again with new bill_number

i tested the changes of bill_number but it created the same.

this bill_number has the same data when i refresh it

    E2101217422
    E2101217425
Tray2's avatar

Change this

  foreach ($no as $idnx) {
                $noo = (int) $idnx->bill_no;
            }

            $tambah = $noo + 1;

To this

  $tambah = (int) $no->bill_no + 1;

Now which path does it take in the if statement?

 if ($request->slave_ID) {
      foreach ($request->slave_ID as $key => $value) {
        $data['slave_id'] =$request->slave_ID[$key],
        Sales::create($data); 
      }

    }else{
      $data['slave_id'] = ($request->has('slave_ID') && count($request->slave_ID) > 0)? count($request->slave_ID) : null;
      Sales::create($data); 
    }
melx's avatar
Level 4

From here am checks if the request has slave_ID then it will save with slave_id

And if not it will save on slave_id as null

That is my logic

Tray2's avatar

Yes, but which of the ones do you get duplicates from?

You really should TDD this stuff.

melx's avatar
Level 4

Both, if test with slave it duplicate and if i did attached slave it duplicate when i refresh the page

MichalOravec's avatar

I think your code could look like something this

$now = now();

$bill_no = (int) DB::table('sales')
    ->selectRaw('max(right(bill_number, 4)) + 1 as bill_no')
    ->whereDate('updated_at', $now->format('Y-m-d'))
    ->value('bill_no');

foreach (Arr::wrap($request->slave_ID ?? 'no_slave_id') as $value) {
    Sales::create($request->only([
        'customer_agent', 'payment_method', 'borderName', 'tag_area', 
        'cargo_type', 'chasisNo', 'ITNo', 'driverName', 'License', 
        'driverPhone', 'subT1', 'TruckNo', 'amount', 'discount', 
        'sale_type', 'currency'
    ]) + [
        'bill_number' => $bill_number = "E{$now->format('dmy')}".Str::padLeft($bill_no, 4, '0'),
        'user_id' => Auth::user()->id,
        'tag_id' => Auth::user()->team_id,
        'unit_issue_id' => $request->unit_id,
        'TrailerNo' => $request->trailerNo,
        'container_no' => $request->containerNo,
        'comments' => $request->comment,
        'created_at' => $request->backdate ?? now()->format('Y-m-d H:i:s'),
        'slave_id' => $value == 'no_slave_id' ? null : $value
    ]);
}

return $this->print_sales_bill_cash($bill_number);

https://laravel.com/docs/8.x/requests#retrieving-a-portion-of-the-input-data

https://laravel.com/docs/8.x/helpers#method-array-wrap

https://laravel.com/docs/8.x/helpers#method-str-padleft

melx's avatar
Level 4

am get this error

     Trying to get property 'bill_no' of non-object

on this line 'bill_number' => $bill_number = "E{$now->format('dmy')}".Str::padLeft((int) $no->bill_no + 1, 4, '0'),

melx's avatar
Level 4

ok seen, but

        Call to a member function value() on array

on this

         $bill_no = (int) DB::select("SELECT max(right(bill_number, 4)) as bill_no from sales WHERE date(updated_at) = '{$now->format('Y-m-d')}'")->value('bill_no') + 1;
MichalOravec's avatar

I would change it to this

$bill_no = (int) DB::table('sales')
    ->selectRaw('max(right(bill_number, 4)) + 1 as bill_no')
    ->whereDate('updated_at', $now->format('Y-m-d'))
    ->value('bill_no');
melx's avatar
Level 4

@michaloravec

Yes i changed, but the it duplicate the slave_id and the bill_no does not increment

Bill is the same but slaveId is duplicated, but if i there is not slaveId it does not duplicate unit_id

MichalOravec's avatar

So solve it by yourself, it's just pure logic. I wasn't thinking about the logic too much.

melx's avatar
Level 4

@michaloravec

                 public function store(Request $request)
              {

          $now = now();
          $bill_no = DB::table('sales')
              ->selectRaw('max(right(bill_number, 4)) as bill_no')
              ->whereDate('updated_at', $now->format('Y-m-d'))
              ->value('bill_no');

          foreach (Arr::wrap($request->slave_ID ?? 'no_slave_id') as $value) {
              Sales::create($request->only([
                  'customer_agent', 'payment_method', 'borderName', 'tag_area', 
                  'cargo_type', 'chasisNo', 'ITNo', 'driverName', 'License', 
                  'driverPhone', 'subT1', 'TruckNo', 'amount', 'discount', 
                  'sale_type', 'currency'
              ]) + [
                  'bill_number' => $bill_number = "E{$now->format('dmy')}".Str::padLeft($bill_no, 4, '0'),
                  'user_id' => Auth::user()->id,
                  'tag_id' => Auth::user()->team_id,
                  'unit_issue_id' => $request->unit_id,
                  'TrailerNo' => $request->trailerNo,
                  'container_no' => $request->containerNo,
                  'comments' => $request->comment,
                  'created_at' => $request->backdate ?? now()->format('Y-m-d H:i:s'),
                  'slave_id' => $value == 'no_slave_id' ? null : $value
              ]);
          }


                    Mystock::where('unit_id',$request->unit_id)
                                          ->update([
                                                "status"=>1,
                                          ]);

                if($request->slave_ID){


                          Mystock::whereIn('unit_id',$request->slave_ID)
                                          ->update([
                                                "status"=>1,
                                          ]);
                }
                
                          
          return $this->print_sales_bill_cash($bill_number); //here to h..


              }
MichalOravec's avatar

You miss + 1 in your code

$bill_no = (int) DB::table('sales')
    ->selectRaw('max(right(bill_number, 4)) + 1 as bill_no')
    ->whereDate('updated_at', $now->format('Y-m-d'))
    ->value('bill_no');
melx's avatar
Level 4

@michaloravec , it create data well, but when i refresh the browser it create new request with new bill_number, and the same request

melx's avatar
Level 4

yes your correct @michaloravec , how can i avoid that bill_number to increment with the same request

because we will have many duplicate data

melx's avatar
Level 4

i was tried this sir but still the same i don't know where i did wrong when i using firstOrCreate

melx's avatar
Level 4

if you want to see in my pc this is anydesk id 123 594 911 to connect

Please or to participate in this conversation.