'How to delete quantity and update in database using laravel?

When I am inserting quantity in database, I want to update the quantity in the another table. This is what I have tried so far,

public function insertData(Request $request)
    {
     
        $userProduct = new UserProduct();


            $localStorageData = $request->input('localStorageData');
            $productData = json_decode($localStorageData);
            print_r($productData);
            foreach ($productData as $value) {

                $data_array['qty'] = $value->productQty;
                $data_array['fk_p_id'] = $value->productId;
                $data_array['fk_user_id'] = $request->fkUserId;

                UserProduct::insert($data_array);
            }


    }

In product table I have "id","p_qty"



Solution 1:[1]

without updating it, you can get the total quantity by doing sum operation for the main object

$localStorageData = $request->input('localStorageData');
$productData = json_decode($localStorageData);
$userProduct = new UserProduct();
$userProduct->p_qty = collect($productData)->sum('productQty')

Solution 2:[2]

You can use two methods to accomplish this in Laravel, using model on created and observers:

 <?php

namespace App\Observers;

use App\Models\Transaction;
use Illuminate\Support\Str;

class UserProductObserver
{
  
    public function created(UserProduct $userProduct)
    {
        $product = $userProduct->product;

        $product->p_qty= $product->p_qty+ $userProduct->qty
        $product->save();
    }

}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ayman Elmalah
Solution 2 Durimi