Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Livewire data is converted to an array after render

I have a simple livewire component which initializes with queried data from SQL. Below is code

public $states=[];

public function mount()
{
    $this->states = DB::select("select id,name from hr_states");
}

in the view:

<select class="mt-1">
    <option>...select...</option>
    @foreach($states as $state)
        <option value="{{$state->id}}" wire:key="{{$state->id}}">{{$state->name}}</option>
    @endforeach
</select>

on the first render, it works well but on any update on page (on other events), it throws error Attempt to read property "id" on array pointing to this line <option value="{{$state->id}}" wire:key="{{$state->id}}">{{$state->name}}

So I tried rendering as an array {{$state['id']}} but that throws error Cannot use object of type stdClass as array

like image 561
Curated Prime Avatar asked Jul 08 '26 08:07

Curated Prime


2 Answers

I've had the same issue before & my approach is using a ternary operator in the blade.

so, instead of using

    {{$state->id}}

I use the null coalesce operator

    {{$state->id ?? $state['id']}}

By doing this, if it cannot find the 'state' object with attribute 'id', it will search for the 'state' array with key 'id'.

This is only a workaround method. still can't figure out how to prevent it from converting to an array after render.

like image 125
salwan mahdi Avatar answered Jul 09 '26 21:07

salwan mahdi


class StateComponent extends Component
{  
    public function render()  
    { 
        $states = DB::table("select * from states")->get();  
        return view('livewire.state-component', ['$states'=>$states]) ;
    }   
}

in the view:

<select class="mt-1"> 
    <option>...select...</option> 
    @foreach($states as $state)
        <option value="{{$state->id}}" wire:key="{{$state->id}}"> 
              {{$state->name}}</option>  
    @endforeach
</select>
like image 36
Faran Avatar answered Jul 09 '26 21:07

Faran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!