3

I have a select list, where the first option is disabled, that's way when the user does not choose an valid option, the result of the select list will not be in the request.

In the validation, the field required, if the value of an other field is for example : 1, in case not 1, the field is not required.

The code:

'city_id' => [
'required',
'integer',
Rule::in(City::availableCities()),
],
'district_id' => new DistrictValidation(request('city_id')),

How I can do that, the district_id throw the validation every time, regardless of, it is in the request, or not.

Thanks for answers,

Update: Maybe you see clearly, if the DistrictValidation rule is here:

class DistrictValidation implements Rule
{
    protected $city;
    private $messages;

    /**
     * Create a new rule instance.
     *
     * @param $cityId
     */
    public function __construct($cityId)
    {
        $this->city = City::find($cityId);
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        dd('here');
        if (!$this->city) {
            return false;
        }

        if (!$this->city->hasDistrict) {
            return true;
        }

        $validator = Validator::make([$attribute => $value], [
            $attribute => [
                'required',
                'integer',
                Rule::in(District::availableDistricts()),
            ]
        ]);

        $this->messages = $validator->messages();

        return $validator->passes();
    }
    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
       return optional($this->messages)->first('district_id');
    }
}
1
  • 1
    can you show your full validation code? Commented Oct 17, 2018 at 6:54

4 Answers 4

2

You can use required_if condition defined in laravel validation Here is the link to the proper documentaion Laravel Validation

Validator::make($data, [
    'city_id' => [
        'required',
        'integer',
        Rule::in(City::availableCities()),
    ],
    'district_id'=>[
         'required_with:city_id,',
    ]
]);
Sign up to request clarification or add additional context in comments.

3 Comments

Sorry, but I don't understand this. If you thought about 'required_if:city_id == 1', it is ok, it's work, but I would not like this. I think something like that: 'required_id:city_id = new DistrictValidation... but, of course, it does not work...
"Validation rule required_if requires at least 2 parameters."
Ok, but I don't understand yet, how does the districtValidation rule run?
0

Try this:

'city_id' => [
  'nullable',
  'numeric',
  Rule::in(City::availableCities())
],
'district_id' => new DistrictValidation(request('city_id')),

1 Comment

0

try this :

$myValidations = [
    "city_id" => [
        "required",
        "integer"
    ]
]

// if city_id exists in availableCities so add some rules 
if(collect(city::availableCities)->contains(request("city_id"))){
    $myValidations["district_id"] = new DistrictValidation(request('city_id'))
}

// validate request fields with $myValidations variable

3 Comments

Ok, but if the 'district_id' non exist in the request, the validation will not happen.
@LaszloP why ? If I meant you right you want to validate district_id if city_id exists in availableCities
No. What I would like: For example if the city_id = 1, then the district_id => 'required', if the city_id = 2, then the district_id => 'nullable'
0

try using the required_if validation where the field under validation must be present and not empty if the anotherfield field is equal to any value.

required_if:field,value,...

use it like:

$request->validate([ 'city_id' => 'required|integer|Rule::in(City::availableCities())', 'district_id' => 'required_if:city_id,1', ]);

try to read more laravel validation here

1 Comment

While this might answer the authors question, it lacks some explaining words and links to documentation. Raw code snippets are not very helpful without some phrases around it. You may also find how to write a good answer very helpful. Please edit your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.