samedi 17 avril 2021

am trying to save product price inside billProduct table in every bill created

how to take price column and cost price from Product table and save it to BillProducts Table when creating Bill

this is the BillProducts Model Where i need to insert price and cost price in every time i create bill

class BillProduct extends Model
{
    protected $fillable = [
        'bill_id', 'product_id', 'quantity', 'unit', 'packing', 'remark', 'discount','price','cost_price'
    ];

    protected $appends = ['price','profit'];

    public function product()
    {
        return $this->belongsTo(Product::class)->withDefault();
    }


}

also, I have a product table where I do store all products information :

class Product extends Model
{
    use Translatable;

    public $translatedAttributes = ['description', 'title'];
    public $translationModel = ProductTranslation::class;


    const FILLABLE = ['price', 'quantity', 'cost_price', 'supplier_id','item_code'];
    protected $fillable = self::FILLABLE;

    public function createTranslation(Request $request)
    {
        foreach (locales() as $key => $language) {
            foreach ($this->translatedAttributes as $attribute) {
                $this->{$attribute . ':' . $key} = $request->get($attribute . '_' . $key);
            }
            $this->save();
        }
        return $this;
    }

    public function billProduct()
    {
        return $this->hasMany(BillProduct::class);
    }
}


Now every time I choose a product when creating a bill I need to save the product price also in billProducts Table 

I need to do that to avoid changing the bill total when updating any product 

also i use this function in model to create products in billProducts


    public function createProducts(Request $request)
    {
        foreach ($this->billProducts ?? [] as $billProduct) {
            $billProduct->product->updateQuantity($billProduct->quantity);
            $billProduct->delete();
        }
        $dataArr = [
            'status' => true,
            'item' => $this
        ];

        foreach ($request->products ?? [] as $product) {
            $productObj = Product::findOrFail($product['product_id']);
            if ($productObj->updateQuantity(-1 * $product['quantity'])) {
                $product['bill_id'] = $this->id;
                BillProduct::create($product);
            } else {
                $dataArr['status'] = false;
            }
        }
        $this->save();

        return $dataArr;
    }


enter image description here



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire