1

I'm using the new enum class in my Laravel application and want to validate optional parameters. I'm able to validate enum parameters if I pass them, but if I don't pass anything, I get the error, "Undefined array key".

My enum class is:

enum SortBy: string {
    case DateEntered = 'date_entered';
}

And my validation is:

$validatedData = $request->validate([
    'sortBy' => [new Enum(SortBy::class)]
];

This works if I make a request with my "sortBy" parameter equal to "dated_entered". If I omit "sortBy" though, I get the "undefined" error.

I tried this as well, but no luck:

$validatedData = $request->validate([
    'sortBy' => [new Enum(SortBy::class), 'nullable']
];

Other things I've tried:

$validatedData = $request->validate([
    'sortBy' => ['exclude_if:sortBy,null', new Enum(SortBy::class)]
];
$validatedData = $request->validate([
    'sortBy' => ['nullable', new Enum(SortBy::class)]
];
$validatedData = $request->validate([
    'sortBy' => ['sometimes', new Enum(SortBy::class)]
];
Josh
  • 714
  • 2
  • 8
  • 20
  • I would expect that putting `'nullable'` as the first rule would allow this to work: `'sortBy' => ['nullable', new Enum(SortBy::class)]`, but I don't have a way to verify that. – Tim Lewis Sep 12 '22 at 17:30
  • @TimLewis Thought that might be it, but didn't appear to work. – Josh Sep 12 '22 at 17:33
  • Hmm... interesting. I haven't been able to use `Enum`s and their associated Validation (still on PHP < 8.1), but something similar I use is `'option' => ['nullable', 'in:' . implode(',', Option::OPTIONS)]` (or similar). If the `option` isn't included (or `null`) in the `request` object, it doesn't perform the `in` check. I'm not sure why that similar approach wouldn't work, but I also don't have a way to test for ya... Hopefully someone else has seen this before. I'd suggest editing the tags on this post to `php` and `laravel` to make it visible to more people. – Tim Lewis Sep 12 '22 at 18:47

1 Answers1

1

I figured it out. It was an error in my code elsewhere =/

Enums are so new to me that I was tunnel-visioning.

This worked fine:

$validatedData = $request->validate([
    'sortBy' => [new Enum(SortBy::class)]
];

What the issue ended up being was that I needed to check that "sortBy" was set in my $validatedData variable.

So from this:

$validatedData['sortBy']
    ? SortBy::from($validatedData['sortBy'])
    : null,

To this:

isset($validatedData['sortBy'])
    ? SortBy::from($validatedData['sortBy'])
    : null,
Josh
  • 714
  • 2
  • 8
  • 20