_SOXIT_'s avatar

Livewire updates property collection order somehow

I have very simple livewire class Test, where I set the $products wihin mount function. For some strange reason, when I dd($this->products) my collection order is changed to ASC, not sure why. Any help?

<?php

namespace App\Livewire;

use App\Models\Shop\Product;
use Livewire\Component;

class Test extends Component
{
    public $products;

    public function mount () {
        $this->products = Product::latest()->get();
    }

    public function addToCart() {
        dd($this->products);
    }

    public function render()
    {
        return view('livewire.test');
    }
}
<div>
    @foreach ($this->products as $product)
    <div wire:key="item-{{$product->id}}">
          {{ $product->name }} - 
            <button wire:click="addToCart"  type="button">Test</button>
    </div>
    @endforeach
</div>
0 likes
3 replies
Snapey's avatar

because when the livewire component is re-rendered it does not use the order in mount

Suggest you refactor as below

<?php

namespace App\Livewire;

use App\Models\Shop\Product;
use Livewire\Component;

class Test extends Component
{
    public function addToCart() {
        dd($this->products);
    }

    public function render()
    {

        return view('livewire.test')
            ->with($products, Product::latest()->get());
    }
}
_SOXIT_'s avatar

@Snapey wouldnt this make a query call on each render? How can I make one call how it is, and not affect it after re-rendering?

_SOXIT_'s avatar

@Snapey Also on livewire github they said it was fixed as a bug, it would come out in next release. However until then I am wondering how would this work out..

Please or to participate in this conversation.