Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

HengLayHak's avatar

TypeError in Liveiwire 3

Cannot assign array to property App\Livewire\Card::$cart_items of type Illuminate\Support\Collection

#[Session(key: 'cart_items')]
    public Collection $cart_items;

How to define property with collection

0 likes
2 replies
LaryAI's avatar
Level 58

To resolve the TypeError in Livewire 3, you need to ensure that the property $cart_items is properly initialized as an instance of Illuminate\Support\Collection. The error occurs because you are trying to assign an array to a property that is typed as a Collection.

Here's how you can define and initialize the property correctly:

  1. Import the Collection class at the top of your Livewire component.
  2. Initialize the $cart_items property as a Collection in the component's constructor or mount method.

Here's an example of how you can do this:

<?php

namespace App\Livewire;

use Livewire\Component;
use Illuminate\Support\Collection;

class Card extends Component
{
    #[Session(key: 'cart_items')]
    public Collection $cart_items;

    public function mount()
    {
        // Initialize the cart_items property as a Collection
        $this->cart_items = collect(session('cart_items', []));
    }

    public function render()
    {
        return view('livewire.card');
    }
}

In this example:

  • The #[Session(key: 'cart_items')] attribute is used to bind the session data to the $cart_items property.
  • The mount method initializes the $cart_items property as a Collection using the collect helper function. This ensures that even if the session data is an array, it will be converted to a Collection.

By following these steps, you should be able to avoid the TypeError and properly use the $cart_items property as a Collection in your Livewire component.

HengLayHak's avatar

@LaryAI Property type not supported in Livewire for property: [{"id":2,"title":"Mens Casual Premium Slim Fit T-Shirts ","price":22.3,"description":"Slim-fitting style, contrast raglan long sleeve, three-button henley placket, light weight & soft fabric for breathable and comfortable wearing. And Solid stitched shirts with round neck made for durability and a great fit for casual fashion wear and diehard baseball fans. The Henley style round neckline includes a three-button placket.","category":"men's clothing","image":"https://fakestoreapi.com/img/71-3HjGNDUL._AC_SY879._SX._UX._SY.UY.jpg","rating":{"rate":4.1,"count":259},"qty":1}]

Please or to participate in this conversation.