Level 122
what have you tried?
- get cart
- find index of same item from cart
- set quantity at index
- save cart
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
hello , i built this class to store items in the cart , and i have some problem with update the quantity of the item, any help.
this Cart class
<?php
namespace App;
class Cart
{
private $cart;
public function __construct()
{
if ($this->get() === null)
$this->set($this->empty());
$this->cart = $this->get();
}
public function add(Product $product): void
{
$item = [
'id' => $product->id,
'name' => $product->name,
'price' => $product->price,
'quantity' => 1,
];
if (!$this->exists($item))
{
array_push($this->cart, $item);
}
$this->set($this->cart);
}
public function remove(int $productId): void
{
array_splice($this->cart, array_search($productId, array_column($this->cart, 'id')), 1);
$this->set($this->cart);
}
public function exists($product)
{
foreach ($this->cart as $item) {
if ($item['id'] == $product['id']) {
return true;
}
}
return false;
}
public function clear(): void
{
$this->set($this->empty());
}
public function empty(): array
{
return [];
}
public function get(): ?array
{
return request()->session()->get('cart');
}
private function set($cart): void
{
request()->session()->put('cart', $cart);
}
}
Please or to participate in this conversation.