How to delete session by the array index?

I have a list of orders in a shopping cart. I would like to delete specific items.
I believe that I can do this through the index of the session. I appreciate if any can help!

To delete everything I do it this way:
$session = $this->request->session();
$session->destroy();
return $this->redirect([‘action’ => ‘index’]);


carrinho (array)
0 (App\Model\Entity\Pedido)
product_id** 55
quantity** 1
product (array)
1 (App\Model\Entity\Pedido)
product_id** 56
quantity** 1
product (array)

I believe you can:

$session = $this->request->session();
$session->delete('dot.path.to.value');

If you know the index of the carrinho to delete:

$session = $this->request->session();
$session->delete("carrion.$index");

Or if you need to work from the product index, you could make sure cart line items are inserted on an index that matches their id.

[ 'carrinho'  => [
   56 => (Pedido)
       'product_id' => 56
   ]
]

Thanks for the comment.

I tried:
public function delete()
{
$session = $this->request->session();
$session->delete(“carrinho.$index”);
return $this->redirect([‘action’ => ‘index’]);
}

index.ctp:

<?= $this->Html->link(__('Delete'), ['action' => 'delete']); ?>

But it did not work.
I will do new tests.

In your method you do not define the value of $index. Where is that coming from?

In the background, Session::delete() is using the Hash class to figure out what you want. Hash. https://book.cakephp.org/4/en/core-libraries/hash.html

So your statement would have to evaluate to something like this:

$session->delete(“carrinho.3”);

Understand. This way it works!

$session = $this->request->session();
$session->delete(“carrinho.0”);
return $this->redirect([‘action’ => ‘index’]);

index.ctp:

<?= $this->Html->link(__('Excluir'), ['action' => 'delete']); ?>

But then I need to inform the index. My question is if I have a list of products and decide to remove one from the list. Without needing to inform in the code.

If the product had been saved in the database, I would do something like:

<?= $this->Form->postLink(__('Delete'), ['action' => 'delete', $product->id], ['confirm' => __('Are you sure you want to delete # {0}?', $product->id)]) ?>

But working with session I have doubts.

Based on that sample code you should be able to do this:

public function delete($index)
{
   $session = $this->request->session();
   $session->delete(“carrinho.$index”);
   return $this->redirect(['details-of-where-you-want-to-return-to']);
   // maybe
   // return $this->redirect($this->referrer());
}

index.ctp:

<?= $this->Html->link(__('Delete'), ['action' => 'delete', $product->id]); ?>

You should get a link that looks something like this

http://you.domain.com/your-controller/delete/3

When I inform manual, like this:
$session->delete(‘carrinho.0’);
it works perfectly.

I tried
$session->delete(“carrinho.$index”);
But it does not work!.
I’ll work on it and post the result!

If $session->delete(‘carrinho.0’); works but $session->delete(“carrinho.$index”); does not, then $index does not have 0 in it.

forum cake 01 When I have indexes 0 and 1. When I have the indexes 0 and 1, as in the image. I use $carrinho->delete(‘carrinho.$index’). Does not work!

if you use $carrinho->delete(‘carrinho.0’), I can delete index 0, for example.

doing this way:

public function delete($index = null)
{
$carrinho = $this->request->session();
$carrinho->delete(‘carrinho.$index’);
return $this->redirect([‘action’ => ‘index’]);
}

index.ctp:

<?= $this->Html->link(__('Delete'), ['action' => 'delete', $carrinho->index]); ?>

Your image doesn’t actually show you having indexes 0 and 1, but anyway. Have you checked in your delete function what exactly the value of $index is?

Just noticed that your code now shows $carrinho->delete('carrinho.$index');, where before it was suggested to use $carrinho->delete("carrinho.$index");, and you said you had tried that. Note the double quotes instead of single. That’s pretty critical here!

1 Like

If you aren’t clear on the distinction between single and double quotes, here is the story:

https://www.php.net/manual/en/language.types.string.php

I used double quotes. But that was not the problem. I did a var_dump:

object(Cake\Http\Session)#37 (4) { ["_engine":protected]=> object(Cake\Http\Session\DatabaseSession)#35 (3) { ["_table":protected]=> object(Cake\ORM\Table)#41 (8) { [“registryAlias”]=> string(8) “Sessions” [“table”]=> string(8) “sessions” [“alias”]=> string(8) “Sessions” [“entityClass”]=> string(15) “Cake\ORM\Entity” [“associations”]=> array(0) { } [“behaviors”]=> array(0) { } [“defaultConnection”]=> string(7) “default” [“connectionName”]=> string(7) “default” } ["_timeout":protected]=> int(1440) ["_tableLocator":protected]=> object(Cake\ORM\Locator\TableLocator)#34 (5) { [“locations”:protected]=> array(1) { [0]=> string(11) “Model/Table” } ["_config":protected]=> array(0) { } ["_instances":protected]=> array(4) { [“Sessions”]=> object(Cake\ORM\Table)#41 (8) { [“registryAlias”]=> string(8) “Sessions” [“table”]=> string(8) “sessions” [“alias”]=> string(8) “Sessions” [“entityClass”]=> string(15) “Cake\ORM\Entity” [“associations”]=> array(0) { } [“behaviors”]=> array(0) { } [“defaultConnection”]=> string(7) “default” [“connectionName”]=> string(7) “default” } [“Aros”]=> object(Acl\Model\Table\ArosTable)#157 (8) { [“registryAlias”]=> string(4) “Aros” [“table”]=> string(4) “aros” [“alias”]=> string(4) “Aros” [“entityClass”]=> string(20) “Acl\Model\Entity\Aro” [“associations”]=> array(2) { [0]=> string(4) “acos” [1]=> string(11) “arochildren” } [“behaviors”]=> array(1) { [0]=> string(4) “Tree” } [“defaultConnection”]=> string(7) “default” [“connectionName”]=> string(7) “default” } [“Acos”]=> object(Acl\Model\Table\AcosTable)#166 (8) { [“registryAlias”]=> string(4) “Acos” [“table”]=> string(4) “acos” [“alias”]=> string(4) “Acos” [“entityClass”]=> string(20) “Acl\Model\Entity\Aco” [“associations”]=> array(2) { [0]=> string(4) “aros” [1]=> string(11) “acochildren” } [“behaviors”]=> array(1) { [0]=> string(4) “Tree” } [“defaultConnection”]=> string(7) “default” [“connectionName”]=> string(7) “default” } [“Permissions”]=> object(Acl\Model\Table\PermissionsTable)#151 (8) { [“registryAlias”]=> string(11) “Permissions” [“table”]=> string(9) “aros_acos” [“alias”]=> string(11) “Permissions” [“entityClass”]=> string(27) “Acl\Model\Entity\Permission” [“associations”]=> array(2) { [0]=> string(4) “aros” [1]=> string(4) “acos” } [“behaviors”]=> array(0) { } [“defaultConnection”]=> string(7) “default” [“connectionName”]=> string(7) “default” } } ["_fallbacked":protected]=> array(1) { [“Sessions”]=> object(Cake\ORM\Table)#41 (8) { [“registryAlias”]=> string(8) “Sessions” [“table”]=> string(8) “sessions” [“alias”]=> string(8) “Sessions” [“entityClass”]=> string(15) “Cake\ORM\Entity” [“associations”]=> array(0) { } [“behaviors”]=> array(0) { } [“defaultConnection”]=> string(7) “default” [“connectionName”]=> string(7) “default” } } ["_options":protected]=> array(4) { [“Sessions”]=> array(0) { } [“Permissions”]=> array(1) { [“className”]=> string(32) “Acl\Model\Table\PermissionsTable” } [“Aros”]=> array(1) { [“className”]=> string(25) “Acl\Model\Table\ArosTable” } [“Acos”]=> array(1) { [“className”]=> string(25) “Acl\Model\Table\AcosTable” } } } } ["_started":protected]=> bool(true) ["_lifetime":protected]=> int(1440) ["_isCLI":protected]=> bool(false) }

I tried the product id, but to no avail!
public function delete($id = null)
{
$carrinho = $this->request->session();
$carrinho->delete(“carrinho.$id”);
return $this->redirect([‘action’ => ‘index’]);
}

index.ctp:
<?= $this->Html->link(__('Delete'), ['action' => 'delete', $carrinho->produto->id]); ?>

You haven’t shown anything explaining how you are determining what value to send in as the argument for delete.

How are the indexes on carrinho being generated? How do you determine which ones exist when you are rendering the page? The Html->link is the key because that’s where the value is being set and sent. if you send a valid carrinho key in it will work, otherwise…

$carrinho->produto->id will certainly not work since you’re early picture showing an example session proves that carrinho is not indexed by this id.

But neither did the session show you have a reliable 0 index. That proves that simple view logic that assumes the first link should pass 0 and the second a 1 will not work.

It is strange, because when I enter the index value I can delete it normally, but I cannot pass it by parameter.

I’m generating the array like this:
public function add()
{
$pedido = $this->Pedidos->newEntity();
if ($this->request->is(‘post’)) {
$pedido = $this->Pedidos->patchEntity($pedido, $this->request->getData());
$pedido->produto = $this->Pedidos->Produtos->get($pedido->produto_id, [‘contain’ => [‘Usuarios’]]);
$session = $this->request->session();
$carrinho = $session->read(‘carrinho’);
$carrinho[] = $pedido;

        if(count($carrinho) <= 3){
            $session->write('carrinho', $carrinho);
            $this->Flash->success(__('Pedido Adicionado'));
            return $this->redirect(['action' => 'index']);
        }else{

            return $this->redirect('/usuarios/login');
            $this->Flash->success(__('Continue sua lista. Cadastre-se e aproveite as vantagens!'));
        }

        $produtos = $this->Pedidos->Produtos->find('list', ['limit' => 200]);
        $usuarios = $this->Produtos->Usuarios->find('list', ['limit' => 200]);
        $this->set(compact('pedido', 'produtos', 'usuarios'));
    }
}

If I add two products to the cart, I see how it looks in the image. After that I can have control if I insert the index in the code.

forum cake

I imagined that this way I could get the index by parameter in the method:

<?= $this->Html->link(__('Delete'), ['action' => 'delete', $carrinho->index]); ?>

But what is the $carrinho object in the template? You get its index property but I don’t see that you ever set that variable.

These are the only variables you send to the view template:

$this->set(compact('pedido', 'produtos', 'usuarios'));

You shouldn’t need to imagine anything. You should know exactly what your variables hold in all places, and if you don’t, you can use debug($carrinho) or the like to find out. Just trying to include variables in your link and hoping they’ll work isn’t a good way to attack the problem.

I had to be absent. I debugged ($carrinho->index) and the return is null. That is, $carinho->index is not receiving the value correctly in index.ctp. My problem is precisely this, receiving the index value of the array.

Solved.

foreach($this->Session->read(‘carrinho’) as $index => $carrinho)