skip to Main Content

The calculation of the total price of products with their quantity. the total price exists in the order migration table with a default of 0 value, and I want to put the $res value in the total_price column.

public function store($user_id, Request $request/*,$id*/){
    $validated=$request->validate([
        'name'=>'max:100',
        // 'total_price'=>'required|integer',
        'order_date'=>'required|date|max:15',
        'copon_id'=>'required|numeric',
        'shipping_date'=>'required|date',//shipping method
        'delevary_date'=>'required|date',//shipping method
        'shipping_price'=>'required|integer',
        'products'=>'required|array',
        'products.*.id'=>'required|numeric|exists:products,id',//{products,id}in to validat of the
         sent dataIn is exested id
        'products.*.quantity'=>'required|numeric|min:1',
    ]); ------------------------
    $res = 0;
     foreach($request['products'] as $product) //total price of products with the same product
     buying  in quantety 
     {
        $sum = Product::find($product['id'])->price;
        $res1 = $sum*$product['quantity'];
        $res = $res + $res1;
     }
     $res = ['total_price'];
                 ----------------------------------
     // $order->products()->sync($validated['products']);//the ['products'] is the way to make 
      the id's in array the []
     $valid = collect($validated)->except(['products'])->toarray();//collect is to convert columns 
      from array to collection & the toarray is for converting products from object to array
     $order = User::find($user_id)->orders()->create($valid);
     foreach ( $request['products'] as $product)
     {
         $order->products()->syncWithoutDetaching([$product['id'] => 
         ['quantity' => $product['quantity']]]);
     } 
    //  return $res;
    return $order->load('products','copon');
}

2

Answers


  1. Chosen as BEST ANSWER

    Anther way to solve it $valid = collect($valid)->put('total_price',$res)->toarray();


  2. Update the order model’s total_price attribute with the calculated value and then save the model.

    $order = User::find($user_id)->orders()->create($valid);
    $order->total_price = $res;
    $order->save();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search