All packages
Enums for Laravel
Validation
validationRule() builds a Laravel in:... rule string from values() — the backed values, or the case names on a pure enum — so the allow-list never drifts when cases change:
$request->validate([
'category' => ['required', NewsCategory::validationRule()],
]);
// validationRule() === 'in:hot-news,regular-news,private-news'In a form request
namespace App\Http\Requests;
use App\Enums\NewsCategory;
use Illuminate\Foundation\Http\FormRequest;
final class StoreArticleRequest extends FormRequest
{
/**
* @return array<string, array<int, string>>
*/
public function rules(): array
{
return [
'title' => ['required', 'string', 'max:255'],
'category' => ['required', NewsCategory::validationRule()],
];
}
}Once validated, the value is known to belong to a case, so PHP’s native from() can’t throw:
public function store(StoreArticleRequest $request): RedirectResponse
{
$article = Article::create([
'title' => $request->validated('title'),
'category' => NewsCategory::from($request->validated('category')),
]);
return to_route('articles.show', $article);
}Arrays of values
For a list of values, apply the rule to every element:
$request->validate([
'categories' => ['required', 'array'],
'categories.*' => [NewsCategory::validationRule()],
]);What goes into the rule
- The rule is in: plus values() joined with commas — 'in:0,5,10' for an int-backed enum. Laravel’s in rule compares as strings, so form input like '5' passes.
- On a pure enum it’s built from the case names — 'in:Active,Archived' — and accepts exactly those.
- Laravel reads the list back as CSV, so a value that would break that syntax — an empty one, one containing a comma, or one starting with a double quote — is quoted with its inner quotes doubled. Every other value stays bare.
- Pass the rule as an array element, as above, rather than inside a |-delimited rule string.
use RoundlyConsulting\Enums\Helpers;
enum Separator: string
{
use Helpers;
case Comma = 'a,b';
case Plain = 'c';
}
Separator::validationRule(); // 'in:"a,b",c'Show your open-source love
This package is free and MIT-licensed. If it saves you time, a one-off donation or a Patreon membership keeps it maintained, tested and documented.
More ways to support, including cryptoBy donating, you agree to our donation terms.
Want this built into your product?
We integrate our packages into custom Laravel and AI builds. Tell us what you're working on and we'll reply within 48 hours.