Reputation: 397
Can't get my head around the best way to do this - I have a model that is adding a product to a shopping cart;
$this->db->select('*');
$this->db->from('products');
$this->db->where('product_id',$pid);
$query = $this->db->get();
$products = $query->result_array();
$stock = $products['0']['stock'];
$quantity = 2;
$cart = $this->cart->contents();
$found = false;
foreach($cart as $items)
{
if($pid == $items['id'] ){
if ($items['qty'] + $quantity <= $stock){
$this->cart->update(array(
'rowid' => $items['rowid'],
'qty' => $items['qty'] + $quantity
));
$found = true;
$SEND MESSAGE SAYING ADDED TO CART
}
else {
$found = true;
$SEND MESSAGE SAYING NOT ENOUGH STOCK
}
}
}
if($found == false){
$data = array(
'id' => $products[0]['product_id'],
'name' => $products[0]['name'],
'qty' => $quantity,
'price' => $products[0]['price']
);
if ($quantity <= $stock)
{
$this->cart->insert($data);
}
else {
echo "Not enough stock";
}
}
return $this->cart->contents();
What is the best way to returning a message to the controller so that i can display to the user that the item has been added/there is not enough stock?
I've read i can use "return" - but as i'm using return $this->cart->contents(); at the bottom of the function I'm not sure where to go.
I'm probably looking at this the complete wrong way, but if anybody could tell me the best way to handle this situation I'd be very grateful.
C.
Upvotes: 0
Views: 78
Reputation: 7475
Try something like this:
$data = array();
$data['cart'] = $this->cart->contents();
$data['msg'] = 'Your message here';
return $data;
And, in your controller, just take out the elements as you need, e.g.:
$return = $this->model->function(); //your model return here $return
$cart = $return['cart']; //cart contents
$msg = $return['msg']; //the message added from the model
Upvotes: 1