Laravel IN Validation or Validation by ENUM Values

PhpValidationLaravelEnums

Php Problem Overview


I'm initiating in Laravel. I searched and not found how to validate data with some ENUM values. On below code I need that type must be just DEFAULT or SOCIAL. One or other:

$validator = Validator::make(Input::only(['username', 'password', 'type']), [
    'type' => '', // DEFAULT or SOCIAL values
    'username' => 'required|min:6|max:255',
    'password' => 'required|min:6|max:255'
]);

Is possible?

Php Solutions


Solution 1 - Php

in:DEFAULT,SOCIAL
The field under validation must be included in the given list of values.

not_in:DEFAULT,SOCIAL
The field under validation must not be included in the given list of values.

$validator = Validator::make(Input::only(['username', 'password', 'type']), [
    'type' => 'in:DEFAULT,SOCIAL', // DEFAULT or SOCIAL values
    'username' => 'required|min:6|max:255',
    'password' => 'required|min:6|max:255'
]);

Solution 2 - Php

The accepted answer is OK, but I want to add how to set the in rule to use existing constants or array of values.

So, if you have:

class MyClass {
  const DEFAULT = 'default';
  const SOCIAL = 'social';
  const WHATEVER = 'whatever';
  ...

You can make a validation rule by using Illuminate\Validation\Rule's in method:

'type' => Rule::in([MyClass::DEFAULT, MyClass::SOCIAL, MyClass::WHATEVER])

Or, if You have those values already grouped in an array, you can do:

class MyClass {
  const DEFAULT = 'default';
  const SOCIAL = 'social';
  const WHATEVER = 'whatever';
  public static $types = [self::DEFAULT, self::SOCIAL, self::WHATEVER];

and then write the rule as:

'type' => Rule::in(MyClass::$types)

Solution 3 - Php

Laravel 9+

https://laravel.com/docs/9.x/validation#rule-enum

use App\Enums\ServerStatus;
use Illuminate\Validation\Rules\Enum;
 
$request->validate([
    'status' => [new Enum(ServerStatus::class)],
]);

Enum:

namespace App\Enums;

enum ServerStatus: string {
    case ACTIVE = 'active';
    case INACTIVE = 'inactive';
}

Required PHP 8.1+

Solution 4 - Php

You can use the Rule class as te documentation indicates. For example, having the following definition in a migration:

$table->enum('letter',['a','b','c']);

Now your rules for your FormRequest should put:

class CheckInRequest extends FormRequest
{ 
    public function authorize()
    {
        return true;
    }


    public function rules()
    {
        return [
            'letter'=>[
                'required',
                 Rule::in(['a', 'b','c']),
             ],
        ];
    }
}

Where Rule::in (['a', 'b', 'c']), must contain the values of your field of type "enun"

This is working fine for me on Laravel 8.x

Solution 5 - Php

Laravel 9 php8.1

$request->validate([
    'type' => [new Enum(TypeEnum::class)],
]);

Less or Equal php 8

you can own enum

class BaseEnum
{
    /**
     * Returns class constant values
     * @return array
     */
    public static function toArray(): array
    {
        $class = new \ReflectionClass(static::class);

        return array_values($class->getConstants());
    }

    /**
     * @return string
     */
    public function __toString(): string
    {
        return implode(',', static::toArray());
    }
}

Child enum

class TypeEnum extends BaseEnum
{
    public const DEFAULT = 'default';
    public const SOCIAL = 'social';
}

in validation u can use it in two different ways

first

$request->validate([
        'type' => 'in:' . new TypeEnum(),
    ]);

second

use Illuminate\Validation\Rule;

    $request->validate([
                'type' => Rule::in(TypeEnum::toArray())
            ]);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMaykonnView Question on Stackoverflow
Solution 1 - PhpAlupothaView Answer on Stackoverflow
Solution 2 - PhpAleksandarView Answer on Stackoverflow
Solution 3 - PhpJosh BonnickView Answer on Stackoverflow
Solution 4 - PhpAlexander RamosView Answer on Stackoverflow
Solution 5 - PhpJahongir TursunboyevView Answer on Stackoverflow