Search code examples
laravellaravel-livewire

Object at controller suddenly become array at view


anyone can explain why this happen? i cant access my data at view because it suddenly change to array. I try to check it using var_dumb at controller

public function render()
{
    var_dump($this->provinces);
    return view('livewire.user-address-form');
}

public function mount()
{
    $provinces = Shipment::getProvince();
    if($provinces->code !== 200)
    {
        abort($provinces->code, $provinces->message);
    }
    else
    {
        $this->provinces = $provinces->data;
    }
}

getProvince() method is an API call with the response like this image. Then I assign $this->province to "data"

the result from var_dump is like this:

array(34) { [0]=> object(stdClass)#1417 (2) { ["province_id"]=> string(1) "1" ["province"]=> string(4) "Bali" } [1]=> object(stdClass)#1411 (2) { ["province_id"]=> string(1) "2" ["province"]=> string(15) "Bangka Belitung" } [2]=> object(stdClass)#1429 (2)...

at view I have code like this:

<select wire:model.debounce.800ms="provinceId" id="provinceId"
    class="form-select block rounded-md shadow-sm mt-1 w-full">
    <option value="">-</option>
    @foreach($provinces as $province)
        <option>{{ var_dump($province) }}</option>
    @endforeach
</select>

and the result are like this image

edited: I found this problem when trying to access my data at view. when i using object property syntax it got error "trying to get property of non-object laravel", and when I try using array syntax it got error "Cannot use object of type stdClass as array". I already have the solution but i dont like (encode to json then decode to array). just wanna know why this happen.


Solution

  • My solution:

    convert $province data to array using JSON encode+decode

    $this->provinces = json_decode(json_encode($provinces->data), true);