Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel validate the field on the basis of value of another field

I want to validate two fields i.e. 'type' and 'options' where 'type' field is enum. The 'options' field should be validated only if the value of 'type' field is 'opt'.

$this->validate($request, [
    'type' => 'required|in:opt,number,text,file,image',
    'options'=>the condition I need(if type is 'opt')
]);
like image 279
tayyab_fareed Avatar asked Mar 26 '18 08:03

tayyab_fareed


2 Answers

You can use required_if validation in Laravel.

$this->validate($request, [
    'type' => 'required|in:opt,number,text,file,image',
    'options'=> 'required_if:type,==,opt'
]);

Here is a Documentation link

like image 131
SRK Avatar answered Nov 02 '22 10:11

SRK


You can add validation conditionally like this

$this->validate($request, [
        'type' => 'required|in:opt,number,text,file,image',
        'options'=>($input['type'] == 'opt')?'required':''
    ]);
like image 42
PPL Avatar answered Nov 02 '22 09:11

PPL