Laravel IN Validation or Validation by ENUM Values Laravel IN Validation or Validation by ENUM Values laravel laravel

Laravel IN Validation or Validation by ENUM Values


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']);

:)


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)


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