I have a array of states that is looping in the front-end. I want to validate in the backend that the value is inside the array. I keep getting error that The selected state is invalid.
Blade View
<select wire:model.defer="state" name="state">
@foreach($states as $state)
<option value="{{ $state }}">{{ strtoupper($state) }}</option>
@endforeach
</select>
Controller (Livewire)
public $states = [
'sa', 'vic', 'nsw', 'qld', 'act', 'nt', 'wa', 'tas'
];
protected function rules()
{
$array = [
'state' => 'required|in:$this->states',
];
return $array;
}
My Answer:
The issue is with how you are passing the array of states to the validation rule. You need to use double quotes instead of single quotes in order to interpolate the variable inside the string. Here's the corrected code:
php
protected function rules()
{
$array = [
'state' => 'required|in:' . implode(',', $this->states),
];
return $array;
}
By using `implode(',', $this->states)`, you are converting the array of states into a comma-separated string that can be used in the `in` validation rule. This should now validate that the selected state is within the array of states.
Rate this post
3 of 5 based on 5822 votesComments