Enumerated (enum) types are data types that comprise a static, ordered set of values. They are equivalent to the enum
types supported in a number of programming languages. An example of an enum type might be the days of the week, or a set of status dropdown values of a form.
We can define the enum data type in the database using enum
. An example to create an enum datatype in migration is shown below. It accepts only 'approve'
, 'pending'
, and 'rejected'
values. It will throw an error if tried to insert other values than the listed ones.
.............
$table->enum('status', ['approve', 'pending', 'rejected'])->default('pending');
.............
So, how can we validate the input field for this data type? Well, the answer is simple. We can use in:foo,bar,…
. The field under validation must be included in the given list of values.
<?php
public function rules()
{
return [
'status' => 'required|in:approve,pending,rejected'
];
}
The above code will only accept if the value of the status input field is approve, pending or rejected. It can also be done using Rule class as in the example below.
<?php
.........
$validate = $request->validate([
'status' => ['required', Rule::in(['approve','pending','rejected'])
]);
.........
Bonus
There is also a not_in
function in laravel validation that does exactly inverse of the in
function. The field under validation must not be included in the given list of values.
<?php
......
$validate = $request->validate([
'status' => ['required', Rule::not_in(['approve','pending','rejected'])
]);
......