Home > Software engineering >  How to get from request->value one value at a time inside foreach loop
How to get from request->value one value at a time inside foreach loop

Time:02-04

Hello i have this code in laravel controller and i get an error for a single value:

public function store(Request $request)
    {
        $values = []; 

        $request->validate([
            'order_number' => 'required',
            'client_id' => 'required|exists:clients,id',
            'description' => 'required',
            'products' => 'required|exists:products,id',
            'amount' => 'required',
        ]);

        $order = Order::create($request->all());

        foreach ($request->products as $product) {

                $values[] = [
                    'order_id' => $order->id,
                    'product_id' => $product,
                    'amount' => $request->amount,
                ];

                $amount = Product::find($product);

               $total_value = $request->amount   $amount->amount; //the error happens here

               $amount->update(['amount' => $total_value]);
            }

            $order->products()->attach($values);

            return redirect('/')->with('msg', 'Order Saved successfully!');
        }

All the values come except the $request->amount that comes as array and not as a single value in a row. This is the error i get:

Unsupported operand types: array string

This is the product model:

  protected $fillable = [
        'name',
        'price',
        'amount',
    ];

    public function orders()
    {
        return $this->belongsToMany(Order::class);
    }

And this is dd($request->amount);

enter image description here

CodePudding user response:

Assuming that $request->amount is directly related to $request->products with the index then you would either need to combine products and amount before you send the request or iterate over products with the index.

foreach ($request->products as $index => $product) {

            $values[] = [
                'order_id' => $order->id,
                'product_id' => $product,
                'amount' => $request->amount[$index], //Reference via index
            ];

            $amount = Product::find($product);

           $total_value = $request->amount[$index]   $amount->amount; //Also here
        }
    }
  • Related