LaszloP
LaszloP

Reputation: 301

Laravel validation: rules in required_if

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');
    }
}

Upvotes: 3

Views: 13673

Answers (4)

Exterminator
Exterminator

Reputation: 1246

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,',
    ]
]);

Upvotes: 2

Kapitan Teemo
Kapitan Teemo

Reputation: 2164

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

Upvotes: 0

Zoha
Zoha

Reputation: 586

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

Upvotes: 0

Salim Ibrohimi
Salim Ibrohimi

Reputation: 1391

Try this:

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

Upvotes: 0

Related Questions