How to update qty if the item is already exitst - Codeigniter - php

I am working with Codeigniter cart
my problem is how to update the quantity of items if the item is already exist in the cart.
My model
function addToCart(){
$data = array(
'id' => $this->input->post('product_id'),
'qty' => $this->input->post('qty'),
'price' => $this->input->post('price'),
'name' => $this->input->post('product_name'),
);
$this->cart->insert($data);
redirect(base_url().'shopping-cart-view');
}

This may help:
function addToCart(){
$data = array(
'id' => $this->input->post('product_id'),
'qty' => $this->input->post('qty'),
'price' => $this->input->post('price'),
'name' => $this->input->post('product_name'),
);
/* modification starts */
$db_query = $this->db->get_where('cart', $data) ;
$rows = $query->num_rows();
if($rows > 0){
// update the record
}else{
//insert record..
}
// modification ends
redirect(base_url().'shopping-cart-view');
}

Related

Laravel 8 update product in cart if exists

I'm using a Laravel 8 with darryldecode/laravelshoppingcart Cart Package. I'm struggling a bit with updating product quantity if it exists in users cart.
For example: If cart is empty, while adding a product and then clicking mutliple times on "Add To Cart" it adds only one product and then updates quantity to its maximum. But when I'm adding a second product, and then adding again product 1 it adds another product to the cart. It definitely should not add another product but it has to be restricted to maximum quantity of first product.
My cart store method:
public function store(CartStoreRequest $request) {
$validated = $request->validated();
$product = Product::findOrFail($validated['product_id']);
$rowId = uniqid();
$userID = $validated['user_id'];
// get current user cart
$currentCart = \Cart::session($userID);
if(!empty($currentCart->getContent()->toArray())) {
foreach($currentCart->getContent() as $item) {
$productID = $item->associatedModel->id;
if($productID === $product->id) {
$currentCart->update($item->id, [
'quantity' => [
'relative' => false,
'value' => $product->minStock($item->quantity + $validated['quantity']),
]
]);
} else {
$currentCart->add(array(
'id' => $rowId,
'name' => $product->name,
'price' => $product->price->amount(),
'quantity' => $validated['quantity'],
'associatedModel' => $product,
'attributes' => array(
'first_image' => $product->firstImage,
'formatted_price' => $product->formattedPrice,
'product_stock' => $product->stockCount()
)
));
}
}
} else {
$currentCart->add(array(
'id' => $rowId,
'name' => $product->name,
'price' => $product->price->amount(),
'quantity' => $validated['quantity'],
'associatedModel' => $product,
'attributes' => array(
'first_image' => $product->firstImage,
'formatted_price' => $product->formattedPrice,
'product_stock' => $product->stockCount()
)
));
}
return redirect()->back();
}
I hope that's someone had similar problem and knows how to solve this.
Okay, so the solution is to use product ID as $rowId,
$validated = $request->validated();
$product = Product::findOrFail($validated['product_id']);
$rowId = $product->id;
$userID = $validated['user_id'];
$currentCart = \Cart::session($userID);
$currentCart->add(array(
'id' => $rowId,
'name' => $product->name,
'price' => $product->price->amount(),
'quantity' => $product->minStock($validated['quantity']),
'associatedModel' => $product,
'attributes' => array(
'first_image' => $product->firstImage,
'formatted_price' => $product->formattedPrice,
'product_stock' => $product->stockCount()
)
));
$currentCartContents = $currentCart->get($rowId);
$quantity = $product->minStock($currentCartContents->quantity);
if($currentCartContents->quantity !== $quantity) {
$currentCart->update($rowId, [
'quantity' => [
'relative' => false,
'value' => $quantity,
]
]);
}
return redirect()->back();

Update multiple table

How do I update the two tables, I have 2 tables, order and product, I want to update the product data on the order, I do it with the following code, but the product doesn't want to update
public function update(Request $request, $id , Product $product)
{
$request->validate([
'do_code' => 'required',
'delivery_date' => 'required',
'qty' => 'required',
'user_id' => 'required',
'customer_id' => 'required',
'armada_id' => 'required',
'send_from_id' => 'required',
]);
$data = Delivery_order::find($id);
$data->update($request->all());
if (count($request->product_name) > 0) {
foreach ($request->product_name as $item => $v) {
$data2 = array(
'order_id' => $id,
'product_name' => $request->product_name[$item],
'qty' => $request->qty[$item],
'tonise' => $request->tonise[$item]
);
$product->update($data2);
}
}
return redirect('/do')->with('success', 'Data Successfully Updated');
}
Use just like this
$product->order_id = $id,
$product->product_name = $request->product_name[$item],
$product->qty = $request->qty[$item],
$product->tonise = $request->tonise[$item]
$product->save();
I think, you can use Laravel Relationship to update the second table.

values does not adds to array dynamically

In CodeIgniter, I want to add values to an array from two different functions, but the values are being added to the array only inside the first function. Please tell what can be the issue?
Code:
public $ChnCat_tags = array();
function first_function() {
//some code
$ChnCat_tags[] = array(
'level' => $level,
'value' => $row_vct->id_vct,
'label' => $row_vct->displayname_vct,
'disable' => $disb
);
$recursion_result = second_function($ChnCat_tags);
return $ChnCat_tags; //only returns values added inside first_function
}
function second_function($ChnCat_tags) {
//some code
$ChnCat_tags[] = array(
'level' => $level,
'value' => $row_vct->id_vct,
'label' => $row_vct->displayname_vct,
'disable' => $disb
);
recursion_result = second_function($ChnCat_tags);
return recursion_result;
}
Well you could just start using $this->ChnCat_tags instead of just ChnCat_tags everywhere.
Or (pass by reference):
function first_function() {
//some code
$ChnCat_tags[] = array(
'level' => $level,
'value' => $row_vct->id_vct,
'label' => $row_vct->displayname_vct,
'disable' => $disb
);
second_function($ChnCat_tags);
return $ChnCat_tags;
}
function second_function(&$ChnCat_tags) {
//some code
$ChnCat_tags[] = array(
'level' => $level,
'value' => $row_vct->id_vct,
'label' => $row_vct->displayname_vct,
'disable' => $disb
);
second_function($ChnCat_tags);
// no need to return now
//return recursion_result;
}
do like this
function first_function() {
$ChnCat_tags[] = array(
'level' => $level,
'value' => $row_vct->id_vct,
'label' => $row_vct->displayname_vct,
'disable' => $disb
);
# Must call function with $this
$recursion_result = $this->second_function($ChnCat_tags);
# print the value of $recursion_result whish hold entire data
print_r($recursion_result);
}
function second_function($ChnCat_tags) {
$ChnCat_tags[] = array(
'level' => $level,
'value' => $row_vct->id_vct,
'label' => $row_vct->displayname_vct,
'disable' => $disb
);
# just return the array data.
return $ChnCat_tags;
}

PHP script to export products to XML per store?

So, I have a daily cron job running a file that calls another file that in combination export our product list to an XML file. These are the two files.
arrayxml.php
<?php
class ArrayXml {
private $xml;
public function __construct($root='store') {
$this->xml = new SimpleXMLElement("<$root></$root>");
}
private function iterate($element, $xmlNode) {
foreach($element as $name=>$value) {
if(is_string($value) || is_numeric($value)) {
$xmlNode->$name = $value;
}
else {
$xmlNode->$name = null;
$this->iterate($value, $xmlNode->$name);
}
}
}
public function toXML($array) {
$this->iterate($array, $this->xml);
return $this->xml->asXML();
}
}
?>
and export.php
<?php
header('Content-Type: text/xml');
include '../app/Mage.php';
include 'arrayxml.php';
Mage::app();
$_products = Mage::getModel('catalog/product')->getCollection();
$_result = array();
foreach($_products as $_product) {
$_product = $_product->load();
$categoryIds = $_product->getCategoryIds();
if (isset($categoryIds[0])){
$category = Mage::getModel('catalog/category')->setStoreId(Mage::app()->getStore()->getId())->load($categoryIds[0]);
$categoryName = $category->getName();
}
$_result['products']['product'][] = array(
'productId' => $_product->getSku(),
'title' => $_product->getName(),
'description' => $_product->getDescription(),
'price' => $_product->getFinalPrice(),
'image' => 'http://dissios.com/media/catalog/product'.$_product->getImage(),
'url' => 'http://dissios.com/'.$_product->getUrlPath(),
'instock' => 'Y',
'availability' => 'Διαθέσιμο',
'category_id' => $categoryIds[0],
'category_name' => $categoryName
);
}
$_converter = new ArrayXML();
echo $_converter->toXML($_result);
$f = fopen("bestprice.xml", "w");
fwrite($f, $_converter->toXML($_result));
fclose($f);
?>
Since then, I've split the site to separate stores/views, so there are two domains that i want the products to have URLs of, not the parent store's (dissios.com in the code above).
I'd like this code to check the store code and adjust the URL accordingly, so I'd have for example http://eclock.gr/media/catalog/product'.$_product->getImage() for the one and http://lourakiahirsch.gr/media/catalog/product'.$_product->getImage() for the other.
Thanks!
EDIT: Solved!
Here is the code i changed:
// Get the product's store IDs
$storeCode = $_product->getStoreIds();
if ($storeCode[2] == '5') {
$_result['products']['product'][] = array(
'productId' => $_product->getSku(),
'title' => $_product->getName(),
'description' => $_product->getDescription(),
'price' => $_product->getFinalPrice(),
'image' => 'http://lourakiahirsch.gr/media/catalog/product'.$_product->getImage(),
'url' => 'http://lourakiahirsch.gr/'.$_product->getUrlPath(),
'instock' => 'Y',
'availability' => 'Διαθέσιμο',
'category_id' => $categoryIds[0],
'category_name' => $categoryName
);
}
else if ($storeCode[2] == '6') {
$_result['products']['product'][] = array(
'productId' => $_product->getSku(),
'title' => $_product->getName(),
'description' => $_product->getDescription(),
'price' => $_product->getFinalPrice(),
'image' => 'http://eclock.gr/media/catalog/product'.$_product->getImage(),
'url' => 'http://eclock.gr/'.$_product->getUrlPath(),
'instock' => 'Y',
'availability' => 'Διαθέσιμο',
'category_id' => $categoryIds[0],
'category_name' => $categoryName
);
}
else {
$_result['products']['product'][] = array(
'productId' => $_product->getSku(),
'title' => $_product->getName(),
'description' => $_product->getDescription(),
'price' => $_product->getFinalPrice(),
'image' => 'http://dissios.com/media/catalog/product'.$_product->getImage(),
'url' => 'http://dissios.com/'.$_product->getUrlPath(),
'instock' => 'Y',
'availability' => 'Διαθέσιμο',
'category_id' => $categoryIds[0],
'category_name' => $categoryName
);
}
As one possible way to do this, you can store your stores' ID (you can find them in Magento Admin panel) in one array and then loop through them using something like this:
foreach($arrayOfStores as $storeId) {
$store = Mage::app()->getStore($storeId);
And then you load your collection:
$collection = Mage::getModel('catalog/product')
->getCollection()
->setStoreId( $storeId )
->addAttributeToSelect('*');

Codeigniter add a Discount item

Hi I have a cart in Codeigniter that works well. I tried to look for a discount/coupon handling but can't.
This is my cart code:
public function addToCart($id){
$this->load->model('products_model');
$products = $this->products_model->getItemDetail($id);
foreach ($products as $product) {
$insert = array(
'id' => $product->id,
'name' => $product->name,
'qty' => '1',
'price' => $product->item_eur,
'image' => $product->image,
'options' => array(
'info' => $product->cart_description,
'qty_description' => $product->qty_description
)
);
$this->cart->insert($insert);
}
$last = end($this->cart->contents());
echo $last['rowid'];
}
I thought of making a Coupon Code read from the DB and insert a discount as an item in the cart:
public function addCoupon(){
$this->load->model('products_model');
$res = $this->products_model->getCoupon($_POST['value']);
if($res){
foreach($res as $result){
$coupon = array(
'id' => $result->id,
'name' => $result->name,
'qty' => '1',
'price' => $result->discount,
'options' => array(
'info' => 'coupon',
'qty_description' => ''
)
);
$this->cart->insert($coupon);
}
echo '1';
}else{
$this->lang->load('products');
echo $this->lang->line('cart_notok');
}
}
Where the DB is
[name:type] (example)
id:int (1)
name: varchar ('Discount of 20€')
code: varchar ('AFD1234')
discount: decimal (-20)
[Edit]
And the model:
public function getCoupon($code){
$results = $this->db->get_where('coupons', array('code' => $code));
return $results->result();
}
The item gets added to the cart but if the 'price' => $result->discount is set to -20 or a percentage it gets set as +20€ and not -20€.
Any way to do this?

Categories