Search code examples
phplaravellaravel-livewire

Laravel validation value in array - livewire


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;
}

Solution

  • Try this

    protected function rules()
    {
        $array = [
        'state' => 'required|in:'.implode(',',$this->states),
        ];
    
        return $array;
    }
    

    or

      protected function rules()
        {
            $array = [
            'state' => ['required',Rule::in($this->states)],
            ];
        
            return $array;
        }
    

    Ref:https://laravel.com/docs/8.x/validation#rule-in