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
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With