Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Required if greater than 0 not working in laravel

Tags:

laravel-5

I am using laravel 5.1

I required one field if another field value is greater than 0.

I tried like this

'scope' => 'required_if:project,>,1',

This code is working if project field value is == 1 but if project value is == 2 then it's not worked

Please give me proper solution

like image 215
Komal Avatar asked Apr 15 '17 11:04

Komal


2 Answers

From the Laravel documentation:

required_if:anotherfield,value,...

The field under validation must be present and not empty if the anotherfield field is equal to any value.

You cannot, therefore, use the > comparison with the values you pass. You have two options, in my view. Either you 1) invert the logic of the requirement, in case the values below 1 are very limited (i.e. the number can be either 0 or 1, but never below zero) or you create a custom validation rule.

Here's how the first option would look:

'scope' => 'required_unless:project,0,1',

Which means: "scope" is only required if project is not 0 or 1 (or greater than 1). Again, this would only work if project cannot be less than zero, or any decimal between 0 and 1, etc.

like image 140
Tomas Buteler Avatar answered Nov 10 '22 12:11

Tomas Buteler


you can use the following :

$v = Validator::make($data, [
    'project' => 'required|integer',
]);

$v->sometimes('scope', 'required', function ($input) {
    return $input->project > 0;
});

hope that it is not too late ! I searched for the same question then i found this solution

for more info ! check this link to Docs

like image 1
Tarek B Avatar answered Nov 10 '22 11:11

Tarek B