vendredi 23 février 2018

Laravel Elequent get the ID before save()

I have a need of getting the ID i'm going to create before it is actually created, I have tried getting the Last ID, but got in to a pickle, because if you delete all the items id DB, there is no "Last" ID. So now I worked it around by Creating and instantly Updating in the same Store() function. Not sure if this eats a lot of resources (probbably not) but just for curiosity and performance sake any tips on how to do it better?

Here is the code:

      $var = $request['purchase_date'];
      $date = implode("-", array_reverse(explode("/", $var)));
      $year = date('y'); 

      $Purchase = new Purchase;
      $Purchase->purchase_number = $request['purchase_number'];
      $Purchase->purchase_date = $date;
      $Purchase->buyer = $request['buyer'];
      $Purchase->object = $request['object'];
      $Purchase->salesman = $request['salesman'];
      $Purchase->created_by = Auth::id();
      $Purchase->order = 'temp'; //Adds Temp order number
      $Purchase->save();

      //Updates Order number to the right one.
      $purchaseUpdate = Purchase::where('id', $Purchase->id)->first();
      $purchaseUpdate->order = $year.'P'.sprintf("%03d", $Purchase->id).'/'.$request['order'];
      $purchaseUpdate->update();

P.S Probbably would be best if I set the Order (temp) to null tho?

Why do I need this? Well the list number has to be the same as the Order number.

For ex:

list == 1

order == 18P001/X.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2sL4KkN
via IFTTT

Aucun commentaire:

Enregistrer un commentaire