required_if Laravel 5 validation required_if Laravel 5 validation php php

required_if Laravel 5 validation


assuming that list_type is the name of the select box to choose from (values : selling or rent)

use it this way

"sale_price" => "required_if:list_type,==,selling"

what does this mean?:

the sale price is only required if the value of list_type is equal to selling

do the same for rent_price

edit

public function rules(){  return [   'list_type'  => 'required',   'sale_price' => 'required_if:list_type,==,For Sale',   'rent_price' => 'required_if:list_type,==,For Rent'}


There can be another situation when, the requirement will be required if another field is not present, if someone is in this situation, you can do

'your_field.*' => 'required_unless:dependency_field.*,


You could use the Illuminate\Validation\Rules\RequiredIf rule directly.

Note: This rule is available in Laravel 5.6 and up.

class SomeRequest extends FormRequest{    ...    public function rules()    {        return [            'sale_price' => new RequiredIf($this->list_type == 'For Sale'),            'rent_price' => new RequiredIf($this->list_type == 'For Rent'),        ];    }}

And if you need to use multiple rules, then you can pass in an array.

public function rules(){    return [        'sale_price' => [            new RequiredIf($this->list_type == 'For Sale'),            'string',            ...        ]    ];}