Skip to content

Instantly share code, notes, and snippets.

@ohryan
Created February 21, 2023 05:11
Show Gist options
  • Save ohryan/26578fe213d3f430c414b70ea914df0d to your computer and use it in GitHub Desktop.
Save ohryan/26578fe213d3f430c414b70ea914df0d to your computer and use it in GitHub Desktop.
Validate a list a comma-seperated list against an Enum
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class EnumList implements Rule
{
private $enumClass;
public function __construct($enumClass)
{
$this->enumClass = $enumClass;
}
public function passes($attribute, $value): bool
{
$validValues = [];
foreach ($this->enumClass::cases() as $enum) {
$validValues[$enum->name] = $enum->value;
}
$inputValues = collect(explode(',', $value))->map(fn ($v) => trim($v));
return $inputValues->diff(collect($validValues))->isEmpty();
}
public function message(): string
{
return "The :attribute values are not valid.";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment