It tells you that the the array of roles does not contain an object. So do a dd on roles and see what it contains.
Jul 13, 2021
5
Level 1
Error when I use livewire to get the value of a select generated by @foreach
I want to show an input field when I select a concrete option in a select.
This code works,
<?php
namespace App\Http\Livewire;
use Livewire\Component;
class Nia extends Component
{
public $roles;
public $role;
public $show = false;
public function change()
{
$this->role == 2 ? $this->show = true : $this->show = false;
}
public function render()
{
return <<<'blade'
<div class="col-span-6 sm:col-span-4 grid gap-6">
<div class="lg:flex grid gap-6">
<!-- Rol -->
<div class="col-span-6 lg:col-span-2 w-full">
<x-jet-label for="role" value="{{ __('Role') }}" />
<select id="role" name="role" wire:model="role" wire:change="change"
class="mt-1 block w-full border-gray-300 focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50 rounded-md shadow-sm">
<option value="">{{__('Choose an option')}}</option>
<option value="0" {{old('role') == 0 ? 'selected' : '' }}>{{__('Admin')}}</option>
<option value="1" {{old('role') == 1 ? 'selected' : '' }}>{{__('Teacher')}}</option>
<option value="2" {{old('role') == 2 ? 'selected' : '' }}>{{__('Student')}}</option>
</select>
<x-jet-input-error for="role" class="mt-2" />
</div>
<!-- NIA -->
<div class="col-span-6 lg:col-span-2 w-full">
@if($show)
<x-jet-label for="nia" value="{{ __('Student identification number') }}" />
<x-jet-input id="nia" name="nia" type="text" class="mt-1 block w-full" value="{{ old('nia') }}" required="required" minlength="7" />
<x-jet-input-error for="nia" class="mt-2" />
@endif
</div>
</div>
</div>
blade;
}
}
but if I change the select for this:
<select id="role" name="role" wire:model="role" wire:change="change"
class="mt-1 block w-full border-gray-300 focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50 rounded-md shadow-sm">
<option value="">{{__('Choose an option')}}</option>
@foreach($roles as $rol)
<option value="{{$rol->id}}" {{old('role') == $rol->id ? 'selected' : '' }}>{{__($rol->name)}}</option>
@endforeach
</select>
when I use @foreach I get the following error:
ErrorException Trying to get property 'id' of non-object
I don't really understand the problem. Can someone explain to me where the problem may be or put me on track to further investigate?
Please or to participate in this conversation.