Laravel required_if does not accept other parameters - php

I have some problems with Laravel's validation. I'm using required_if validator.
What I want to achieve: When the hilightColorBool is true the hilightColor should be required, should be integer between min:1 and max:5.
...
'hilightColorBool' => 'required|boolean',
'hilightColor' => 'required_if:hilightColorBool,1|integer|min:1|max:5'
...
But when I'm doing it like above it always returns that hilghtColor is bool, when I do remove the integer, min and max from hilightColor it works good, but I need to validate anyway if it is integer between 1 and 5. It seems weird to me.

Going on from my comment, i may do it like this:
$rules = [
'hilightColorBool' => 'required|boolean',
];
if (is_bool($request->get('hilightColorBool'))) {
$rules['hilightColor'] = 'required|integer|min:1|max:5';
}
then simply do:
$request->validate($rules);

Related

Laravel: Using validator's sometimes method when input is an array

I have a form that posts a structure field as an array. The structure array contains definitions of database table columns.
$validator = Validator::make($request->all(), [
'structure' => 'required|array|min:1',
'structure.*.name' => 'required|regex:/^[a-z]+[a-z0-9_]+$/',
'structure.*.type' => 'required|in:integer,decimal,string,text,date,datetime',
'structure.*.length' => 'nullable|numeric|required_if:structure.*.type,decimal',
'structure.*.default' => '',
'structure.*.index' => 'required_if:is_auto_increment,false|boolean',
'structure.*.is_nullable' => 'required_if:is_auto_increment,false|boolean',
'structure.*.is_primary' => 'required_if:is_auto_increment,false|boolean',
'structure.*.is_auto_increment' => 'required_if:structure.type,integer|boolean',
'structure.*.is_unique' => 'required_if:is_auto_increment,false|boolean',
'structure.*.decimal' => 'nullable|numeric|required_if:structure.*.type,decimal|lt:structure.*.length',
]);
Without going into explanation of all the rules, one thing should be made sure that the length field is always null when the type is not string or decimal as you cannot assign a length to columns other than these types. So, I am trying to use the sometimes method on the $validator instance.
$validator->sometimes('structure.*.length', 'in:null', function ($input) {
// how to access the structure type here?
});
My question is inside the closure, how do I make sure that the length is null only for the array element that has the type set to other than string or decimal.
I have tried the dd function and it seems the whole input array is passed to the closure.
$validator->sometimes('structure.*.length', 'in:null', function ($input) {
dd($input);
});
Here is the output of the dd method.
I can use a foreach construct but wouldn't that be inefficient? Checking all the elements for a single element?
How do I check the type only for the array element under consideration?
Is there a Laravel way to do this?
How about thinking opposite? if the Type is String or Decimal, the Length field will become Required.
$validator->sometimes('structure.*.length', 'required', function ($input) {
return $input->type == 'string' or $input->type == 'decimal';
});
This is a great question. I took a look at the API for sometimes(). It seems, what you want to do, is currently not possible with it.
A possible alternative could be to use an After Validation Hook. For example:
$validator->after(function ($validator) {
$attributes = $validator->getData()['structure'];
foreach($attributes as $key => $value) {
if(! in_array($value['type'], ['string', 'decimal']) && ! is_null($value['length'])) {
$validator->errors()->add("structure.{$key}.length", 'Should be null');
}
}
});

Is there a way to check if a couple of inputs are unique in laravel 5.2?

update
What I have is a table with these columns:
- ID
- production_year
- type
If the type is already present in the table with the value the user wants to pass, check if production_year is already present too, but fail the validation ONLY if these values are present in the same record. Otherwise let the user to store this record.
I'm trying to check the uniqueness of a couple of fields in the same record...
I've seen the documentation about the conditional validation, but I didn't quite find the answer there.
the code
public function rules()
{
return [
// I'd like to check the uniqueness of both of them. In the same record
'production_y' => 'required|unique',
'fk_type' => 'required|unique',
];
}
Any idea? Thanks!
Laravel 5.3 Update:
Now, you can generate the same rule fluently using the Rule (\Illuminate\Validation\Rule) class.
NULL,id part of the string way is no more required. See:
public function rules()
{
$type = $this->get('fk_type');
return [
'production_y' => [
'required',
Rule::unique('your_table', 'production_year')->where(function($query) {
$query->where('type', $type);
}),
],
];
}
Original Answer
Can't test right now, can you try:
public function rules()
{
$type = $this->get('fk_type');
return [
'production_y' => "required|unique:your_table,production_year,NULL,id,type,{$type}",
// ...
];
}
Explaination:
unique:your_table Set the table for the unique check.
,production_year This matches with production_y.
,NULL,id check all the records.
3.1. if you use like {$id},id it will check uniqueness except the record with the {$id},
,type,{$type} and the type should be {$type}
That will produce sth. like (not exact query, just to express the idea):
select count(*) from your_table where production_year = $product_y and where type = $type and where id <> null
if someone cames from laravel 8, i tried this and it worked !!
for me i need to check the uniqueness of (category_id,subcategory_id) which mean you can find (1,2),(1,3),(2,1),(2,3) but you cant find similar couple !!
'category' => "required|unique:tickets,category_id,NULL,id,subcategory_id,{$request->input('subcategory')}"

Laravel validate int or float numbers as string

in my project. all mount maybe int or float or was even double.in database amount column type is varchar and for each choose amount by user i have simple limitation, for example amount must be more than some value and less that some value. but i get error validation in laravel.
$ps = DB::table('merchant_web_service')->whereCustomerKey($request->input('customer_key'))->first();
/* $ps->minimum_range_buy is 5 and $ps->maximum_range_buy is 10*/
$validate_amount = Validator::make($request->all(),
['amount' => "required|min:$ps->minimum_range_buy|max:$ps->maximum_range_buy"]);
validator error is:
"The amount must be at least 10 characters."
my test amount values: 1000,100.1
Since you didn't specify any rule for the input data type, it validates it as a string. Try numeric and between rules.
$validate_amount = Validator::make($request->all(),
['amount'=>
"required|numeric|between:$ps->minimum_range_buy,$ps->maximum_range_buy"
]);
try this
$rules = [
'your_field' => 'required|regex:/^\d*(\.\d{2})?$/'
]

Laravel form input integer length

In Laravel form input validation, you can specify a minimum and a maximum length of a given input field.
$inputRules = [
'postCode' => 'min:3|max:8'
];
Validation outcome
'BA45TZ' = true
'FF' = false
'GH22 55XYZ' = false
However if I do the same for a number, it will validate whether the input is less than or greater than the input, then return on that.
$inputRules = [
'cv2' => 'min:3|max:4'
];
Validation outcome
'586' = false
'4' = true
'2' = false
'3' = true
I actually want to validate a numbers length not it's numerical value. I can't figure out how to do this. Google has been no help, or I am not searching the right thing.
Anybody had any experience with this?
EDIT: I have answered my own question. I had missed Laravels digits_between.
Like an idiot, I missed Laravels digits_between validator rule. I swear I had scoured those rules, but here we are.
Thank you everyone for your help.
$inputRules = [
'cv2' => 'required|numeric|digits_between:3,4'
];
That's the expected behavior of Laravel's size, min and max validations. You can't change it.
For string data, value corresponds to the number of characters. For numeric data, value corresponds to a given integer value. For files, size corresponds to the file size in kilobytes.
To solve this you have to create a custom validation rule.
Something like this:
Validator::extend('min_length', function($attribute, $value, $parameters){
return strlen($value) >= $parameters[0];
});
Validator::extend('max_length', function($attribute, $value, $parameters){
return strlen($value) <= $parameters[0];
});
And you can use them in the same way:
'cv2' => 'min_length:3|max_length:4'
For length in number you've to use size, but you can't put ranges in it. So, the best thing to do is making a custom validation.
Here is the documentation in laravel: http://laravel.com/docs/5.0/validation#custom-validation-rules
And an example:
Validator::extend('minsize', function($attribute, $value, $parameters)
{
return strlen($value) >= $parameters[0];
});
And do the same with maxsize.

Laravel rule validation for numbers

I have the following rules :
'Fno' => 'digits:10'
'Lno' => 'min:2|max5' // this seems invalid
But how to have the rule that
Fno should be a digit with minimum 2 digits to maximum 5 digits and
Lno should be a digit only with min 2 digits
If I correctly got what you want:
$rules = ['Fno' => 'digits_between:2,5', 'Lno' => 'numeric|min:2'];
or
$rules = ['Fno' => 'numeric|min:2|max:5', 'Lno' => 'numeric|min:2'];
For all the available rules: http://laravel.com/docs/4.2/validation#available-validation-rules
digits_between :min,max
The field under validation must have a length between the given min
and max.
numeric
The field under validation must have a numeric value.
max:value
The field under validation must be less than or equal to a maximum
value. Strings, numerics, and files are evaluated in the same fashion
as the size rule.
min:value
The field under validation must have a minimum value. Strings,
numerics, and files are evaluated in the same fashion as the size
rule.
$this->validate($request,[
'input_field_name'=>'digits_between:2,5',
]);
Try this it will be work
The complete code to write validation for min and max is below:
$request->validate([
'Fno' => 'integer|digits_between:2,5',
'Lno' => 'min:2',
]);
Laravel min and max validation do not work properly with a numeric rule validation. Instead of numeric, min and max, Laravel provided a rule digits_between.
$this->validate($request,[
'field_name'=>'digits_between:2,5',
]);
Also, there was just a typo in your original post.
'min:2|max5' should have been 'min:2|max:5'.
Notice the ":" for the "max" rule.
In addition to other answers, i have tried them but not worked properly. Below code works as you wish.
$validator = Validator::make($input, [
'oauthLevel' => ['required', 'integer', 'max:3', 'min:1']
]);

Categories