1

I'm having one more problem in the logical realm.

I have an array containing ids:

$product_ids = ['1', '5', '3']; <- Example

Another string that I convert to an array separating it by commas, this to indicate the quantities of the products to be withdrawn. For example for product 1 I want 3 drives so I would need the array element to be "1,3".

$finalarray = ["1,3", "5,2", "3,10"];

Next I indicate the code that is executed in the controller (where is what I previously told):

public function ordenform(Request $request)
{

    $input = $request->all();

    $request->validate([
        'nombre' => 'required|string',
        'apellido' => 'required|string',
        'productos' => 'required',
        'cantidades' => 'required|string',
        'enviosino' => 'required|in:si,no',
    ]);

    // Quantity Array
    $cantidades = explode(',', $input['cantidades']);
    if (count($cantidades) != count($input['productos'])) {
        return back()->withErrors(['Las cantidades no corresponden a los productos agregados']);
    }

    $total = 0;
    $ganancia = 0;

    foreach ($input['productos'] as $producto) {
        $producto = Product::find((int) $producto);
        $total += $producto->value;
        $ganancia += $producto->ganancia;
        $producto->stock = (int) $producto->stock - 1;
        $producto->save();
    }

    if ($input['enviosino'] == 'si') {
        $total += (int) $input['envio'];
    }

    if ($input['envio'] == null) {
        $input['envio'] = 0;
    }

    // Products IDS Array
    $jsonproductos = json_encode($input['productos']);

    Order::create([
        'nombre' => $input['nombre'],
        'apellido' => $input['apellido'],
        'product_ids' => $finalprods,
        'value' => $total,
        'ganancia' => $ganancia,
        'envio' => $input['envio'],
    ]);

    $caja = Config::where('id', 1)->get()->first();
    $caja->dinerototal += $total;
    $caja->gananciatotal += $ganancia;
    $caja->save();

    return back()->with('success', 'Orden creada correctamente');
}

Finally, I need to pass as creation parameter the final array to the column products_ids (later I will modify the name).

Another option I thought of is passing objects to an array:

[{id: 1, quantity: 3}]

But I don't know how to get to create that object, I'm still kind of new hehe.

I hope I have explained myself well, English is not my native language. I'm sorry.

I am attentive to your comments !! Greetings.

PS: I am using Laravel

2 Answers 2

1

To achieve [{id: 1, quantity: 3}] there will be several idea, but it seems to be an arrayList, so below is how you can create an arrayList in PHP. I have not tested the code, just written here, but should give you the idea to achieve this.

I am considering one is Order class.

 <?php
class Order {
        private $id;
        private $quantity;
    
        public function setId(int $id) {
            $this->id = $id;
            return $this;
        }
    
        public function getId(){
            return $this->id;
        }
    
        public function setQuantity(int $quantity) {
            $this->quantity  = $quantity;
            return $this;
        }
    
        public function getQuantity(){
            return $this-> quantity;
        }
    
        public function toArray(){
           return [
               'id' => $this->getId(),
               'quantity' => $this->getQuantity()
           ];
        }
    }
?>

another is OrderList.

<?php
class OrderList {
       private $orderList;
    
       public function __construct(Order ...$orders) {
            $this->orderList = $orders;
       }
     
       public function toArray(){
          $arr = [];
          foreach ($this->orderList as $order) {
            $arr[] = $order->toArray();
          }
          return $arr;
       }
    }
?>

and then use like

$order1 = new Order();
$order1 = $order1->setId(1)->setQuantity(10);
$order2 = new Order();
$order2 = $order1->setId(2)->setQuantity(20);
    
$orderList = new OrderList($order1, $order2);
var_dump(json_encode($orderList->toArray()));

//Output

string(47) "[{"id":2,"quantity":20},{"id":2,"quantity":20}]"

You do not need json_encode, I have added it to print only.

Sign up to request clarification or add additional context in comments.

Comments

0

Nevermind, resolved ->

        $prodsfinal = array();
    for ($i = 0; $i < sizeof($cantidades); $i++) {
        $array = [
            'id' => json_decode($input['productos'][$i]),
            'cantidad' => (int) $cantidades[$i],
        ];
        array_push($prodsfinal, $array);
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.