1

I am using Cakephp 3.0.I am new in cookie concept. I have successfully created a cookie but i want to delete a value from cookie array. Here is my code:-

enter code here
$cookiedata=
Array
(
[0] => 2
[1] => 1
)

$_GET['id'] = 2;

public function cartitems(){
    $cookiedata = $this->Cookie->read('ProductCartdata'); 
    $this->loadModel('Products');
    $query = $this->Products->find('all')->where(['id IN' =>$cookiedata]);
    $products = $query->hydrate(false)->toArray();
        if(isset($_GET['id'])){
            if(($key = array_search($_GET['id'], $cookiedata)) !== false) {
                    unset($cookiedata[$key]);
            } 
    $this->redirect(['controller'=>'test','action' => 'cartitems']);    
   }
        $this->set(compact('products','cookiedata'));
}

And i want that result:-

enter code here
Array
(
[0]=>1
)

1 Answer 1

1

You can read up on the Cookie-component in the documentation. There is a delete-method if you completely want to remove the data in your cookie:

Cookie::delete($key)

In your case it probably makes more sense to write over the existing data after looping:

$this->Cookie->write('ProductCartdata', $cookiedata);
Sign up to request clarification or add additional context in comments.

4 Comments

why we again write cookie after deleting value from array
Well you want to update the Cookie don't you? The long winded answer is. When you read the cookie you get a copy of the data, but it stays the same in the cookie. If you update the data, e.g. by unsetting a key, then you have to update the cookie-data as well. Otherwise the next time you read from the cookie you will get the old data.
so according to you we again write cookie
Yes, we will update the cookie data to write our changes to the cookie again. You can think of your cookie as a kind of database. When you want your changes to stay you have to insert or update in the database. It's the same with data in a cookie.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.