I have this fields:
id, title, type
type is enum And I would like to validate my title by Type column, eg:
id | title | type
1 | test | option1
2| test | option2
So when someone tries to insert a row with this condition, validation should be processed for unique of the column.
3 | test | option1 ==> should not be insert due unique validation rule.
How will my validation rule look like?
Regards
// Edit 1: Rules facade was the solution.
To get the exact words to validate you can make use of Rule::in method available with laravel. Using Rule::in method whatever the values provided by this rule has to be matched otherwise it will fail.
Laravel Form Request class comes with two default methods auth() and rules() . You can perform any authorization logic in auth() method whether the current user is allowed to request or not. And in rules() method you can write all your validation rule.
in:option1,option2 The field under validation must be included in the given list of values.
not_in:option1,option2 The field under validation must not be included in the given list of values.
You'r validation should look like the following, but it requires your to hard code your options in "in" parameters or 'implode' an array.
$validator = Validator::make(Input::only(['title', 'type']), [
'type' => 'in:option1,option2, // option1 or option2 values
'title' => 'required|min:6|max:255', //whatever rules you want ..
]);
You can avoid 'implode' by this way:
$validator = Validator::make(Input::only(['title', 'type']), [
'type' => Rule::in(['option1', 'option2']), // option1 or option2 values
'title' => 'required|min:6|max:255', //whatever rules you want ..
]);
If the type
field is not dynamic, you could use Rule
class to add extra query in your validation rule.
return [
'title' => [
Rule::unique('tablename', 'title')->where(function ($query) {
$query->where('type', 'option1');
})
]
];
else, you can make custom validation rules.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With