Home > Back-end >  How to delete quantity and update in database using laravel?
How to delete quantity and update in database using laravel?

Time:05-11

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"

CodePudding user response:

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')

CodePudding user response:

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();
    }

}
  • Related