darryldecode / laravelshoppingcart

Shopping Cart Implementation for Laravel Framework
1.32k stars 413 forks source link

How can I check the best-selling products? #369

Open alquialrium opened 10 months ago

alquialrium commented 10 months ago

After saving the order data in the database, in my controller i do the following:

$carts = Order::all();
$carts->transform(function($order, $key) {
    $order->cart = unserialize($order->cart);
    return $order;
});

and i get 4 products:

Illuminate\Database\Eloquent\Collection {#1538 ▼ // app\Http\Controllers\OrderController.php:119
#items: array:4 [▼

0 => App\Models\Order {#1540 ▶}
1 => App\Models\Order {#1541 ▶}
2 => App\Models\Order {#1542 ▶}
3 => App\Models\Order {#1543 ▶}
]
  #escapeWhenCastingToString: false
}

And the detail of each one:

Illuminate\Database\Eloquent\Collection {#1538 ▼ // app\Http\Controllers\OrderController.php:119
#items: array:4 [▼

0 => App\Models\Order {#1540 ▼
  #connection: "mysql"
  #table: "orders"
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  +preventsLazyLoading: false
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #escapeWhenCastingToString: false
  #attributes: array:5 [▼
    "id" => 1
    "cart" => Darryldecode\Cart\CartCollection {#1509 ▼
      #items: array:1 [▼
        59 => Darryldecode\Cart\ItemCollection {#1537 ▼
          #items: array:6 [▼
            "id" => "59"
            "name" => "PRODUCTO #01"
            "price" => 27.99
            "quantity" => "1"
            "attributes" => Darryldecode\Cart\ItemAttributeCollection {#1536 ▶}
            "conditions" => []
          ]
          #escapeWhenCastingToString: false
          #config: array:6 [▶]
        }
      ]
      #escapeWhenCastingToString: false
    }
    "user_id" => "5"
    "created_at" => "2023-09-07 11:04:42"
    "updated_at" => "2023-09-07 11:04:42"
  ]

How can I access the id and quantity of each product? Since when accessing cart in the array, next is the id and I don't access to the id, I haven´t that information

"cart" => Darryldecode\Cart\CartCollection {#1535 ▼
      #items: array:1 [▼
        83 => Darryldecode\Cart\ItemCollection {#1520 ▼

I use a forech

  foreach($carts as $item)
     {
         $item;
     }   
ultrono commented 1 month ago

Yikes.