on my controller I have:
 public function store(ProductRequest $request)
The request:
class ProductRequest extends Request
{
    public function rules()
    {
        return [
            'name' => 'required|min:3',
            'perTypeTime' => 'sometimes|required',
            'per_type_id' => 'required'
        ];
    }
}
I want to change the perTypeTime rule above to be conditional depending on if per_type_id field == 1.
If I initiated the validator in the controller I believe I could do something like the below:
$v = Validator::make($data, [
    'per_type_id' => 'required|email'
]);
$v->sometimes('perTypeTime', 'required|max:500', function($input)
{
    return $input->per_type_id == 1;
});
Is there a way to do this, while keeping my custom request. I like how this approach keeps the controller cleaner.
I can't seem to access the validator on the request object. Is there a way to specify this condition inside the request itself, or to access the validator from the request object, or is there another way?
You can do that
I want to change the perTypeTime rule above to be conditional depending on if per_type_id field == 1.
within your rules() method in your ProductRequest.
For details see required_if:anotherfield,value in the Laravel documentation validation rules.
public function rules()
{
    return [
        'name'          => 'required|min:3',
        'perTypeTime'   => 'required_if:per_type_id,1',
        'per_type_id'   => 'required'
    ];
}
Laravel 5.3, in your request file you can add:
use Illuminate\Validation\Factory;
...
public function validator(Factory $factory)
{
    $validator = $factory->make($this->input(), $this->rules());
    $validator->sometimes('your_sometimes_field', 'your_validation_rule', function($input) {
        return $input->your_sometimes_field !== null;
    });
    return $validator;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With