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

mateog98's avatar

How to auto calculate fields?

Hi in a table i have three fields, sale_price, discount percentage, and discount (discount amount). Up two now im filling in the fields through inputs in a form. How can i do so that my software calculates itself the discount amount by only filling in the sale_price and discount percentage. I know that the equation should be (sale_price * discount_percentage)/100 = discount_amount, but what i am asking is where should i apply that logic. In my controller?

PresupuestoProductoController:

 public function store(Request $request){
         /*dd($request->all());*/
         $presupuestoProducto = new PresupuestoProducto();
         $presupuestoProducto->presupuesto_id = $request->presupuesto_id;
         $presupuestoProducto->product_id = $request->product_id;       
         $presupuestoProducto->sale_price = $request->sale_price;        
         $presupuestoProducto->discount_percentage = $request->discount_percentage;
         $presupuestoProducto->discount = $request->discount;        
        $presupuestoProducto->save();
        Session::flash('success');
        return redirect()->route('presupuestos-productos.view');
     }
0 likes
3 replies
mateog98's avatar

But i did this in my controller:

        $presupuestoProducto->discount = ($sale_price * $discount_percentage)/100;

I just want to pass that value to my view in this input:

                   <div class="form-group col-md-3">
                        <label for="discount">Descuento</label>
                        <input type="number" name="discount" class="form-control" value="discount">
                    </div>

But without having to input the value manually. How should i do?

   public function add(){
           $presupuestoProducto['presupuestosProductos'] = PresupuestoProducto::all();  
           $presupuestoProducto['presupuestos'] = Presupuesto::all();        
           $presupuestoProducto['products'] = Product::all();
    
            return view('backend.presupuesto_producto.add-presupuesto-producto', $presupuestoProducto);
     }

Please or to participate in this conversation.