How to work with cart library in codeigniter?


Today i will discuss about cart library of CI (Codeigniter) that how to create, update and delete cart. In this tutorial i have assumed that you have basic knowledge of Codeigniter.If not then please follow our Codeigniter basic tutorial.

 Note!  In Codeigniter, Cart utilize the session class so remember that all data save in session with particular row Id.

First of all load or initialize  the cart library in your Controller's construct function like the following:

class Main extends CI_Controller{
  public function __construct(){
   parent::__construct();
   // Load Libraries
   $this->load->library('cart');
  }
 }
Once cart loaded, you can ready to use this like:
$this->cart

Adding Itme in cart

Simple pass an array in cart object.
$data = array(
               'id'      => 'sku_123ABC',
               'qty'     => 1,
               'price'   => 39.95,
               'name'    => 'T-Shirt',
               'options' => array('Size' => 'L', 'Color' => 'Red')
            );
$this->cart->insert($data); 
Important! The first four array indexes above (id, qty, price, and name) are required.If you do not pass these indexes then data will not save in cart.

Delete or Update Cart

if you want to delete cart the simple make the 'qty' index 0 in current cart with rowID like the following:
$data = array(
               'rowid' => 'b99ccdf16028f015540f341130b6d8ec',
               'qty'   => 3
            );

$this->cart->update($data); 
 Note!  Every cart has its own and unique rowId.

If you want to update the cart then you can update the 'qty' variable with your desired value.If you do this then your cart will be updated.

Displaying Your Cart

Displaying cart is very simple as above.
print_r($this->cart->contents()); //Print this in your editor
Array
(
    [5551c02b172187b9eb62a40f191d2eba] => Array
        (
            [rowid] => 5551c02b172187b9eb62a40f191d2eba
            [id] => sku_123ABC
            [qty] => 1
            [price] => 500
            [name] => Hotel Management project
            [options] => Array
                (
                    [img] => college-512.png
                )

            [subtotal] => 500
        )

    [fe8a9d0e9c1f1883840ddfda19acac7f] => Array
        (
            [rowid] => fe8a9d0e9c1f1883840ddfda19acac7f
            [id] => sku_123ABC
            [qty] => 1
            [price] => 100
            [name] => Doctor Patient Managment project
            [options] => Array
                (
                    [img] => 22.jpg
                )

            [subtotal] => 100
        )

)

$this->cart->contents() object contains the current cart data so that we can use this variable to display our cart list.

0 comments:

Ads

Web Hosting