Cannot assign array to property of type Illuminate\Support\Collection

I have the following code and when ever thevariable $categoriesSelected that is of type Collection
is updated on the DOM
I am getting this error: “Cannot assign array to property App\Http\Livewire\ProductForm::$categoriesSelected of type Illuminate\Support\Collection”

Note that at first time it loads and works just fine.

use Illuminate\Support\Collection;

class ProductForm extends Component
{
    public Collection $categoriesSelected;
    public Collection $categories;
    public Product $product;

    public function mount(Product $product)
    {
        $this->product = $product;
        $this->categories = $product->categories()->get();
    }

   public function render()
    {
        return view('livewire.product-form');
    }
}
<select wire:model="categoriesSelected" multiple>
    @foreach($categories as $key => $value)
      <option value="{{ $key }}" wire:key="{{ $key }}">{{ $value }}</option>
    @endforeach
</select>

when you call the relationship $product->categories()->get(), you are retrieving an model’s elocuent collection, so in the foreach you must handle like that

<select wire:model="categoriesSelected" multiple>
    @foreach($categories as $item)
      <option value="{{ $item->id }}" wire:key="{{ $item->id }}">{{ $item->name }}</option>
    @endforeach
</select>

Do you have a Collection Model app\models\Collection.php?

Laravel already has a Collection class Illuminate\Support\Collection that you’re clashing with. Rename your model.

Thanks for the info but I am use the default Laravel Collection. I updated the question.

Like I told you before. But you can declate the categories property without Collection type (public $categories) or in the case you do it, you must loop all the data retrieved (
$product->categories()->get()) and push every item to the collection property.

foreach($product->categories()->get() as $item)
    $this->categories->push($item);

https://laravel.com/docs/8.x/collections