Jeremy
Jeremy

Reputation: 1952

How to do a validation conditional in this case with Laravel?

I have two fields. author_id and teacher_id. I would like one or the other to be required BUT if both are filled, it displays an error saying "there can be only one".

Is it possible to do this with validation rules in Laravel? I do not understand the documentation. Perhaps an example will be more meaningful (and an explanation)

Upvotes: 2

Views: 4248

Answers (3)

tushar zore
tushar zore

Reputation: 101

Here are mention 2 different ways to do conditional validation e.g. Login functionality need fcmToken required if deviceType is "android"

  1. in Controller

public function login(Request $request){
// Validate fcmToken required if deviceType exist and android

if($request->has('deviceType') && $request['deviceType'] == "android") {
$request->validate([ 'fcmToken' => 'required',
);
} }

  1. In Request Extended Class

use Illuminate\Foundation\Http\FormRequest;
class LoginRequest extends FormRequest { public function authorize() { return true; }

    public function rules()
    {
        return [
            'email'    => 'required|string',
            'password' => 'required',
            'fcmToken'    => 'string',
            'deviceType' => 'required|string'
        ];
    } }

Upvotes: 0

Jakub Kratina
Jakub Kratina

Reputation: 664

Sometimes is better to use custom after validation hook, for example:

/**
 * @return \Illuminate\Validation\Validator
 */
public function validator(): \Illuminate\Validation\Validator
{
    $validator = Validator::make($this->all(), [
        'file' => 'required_without:url|file',
        'url'  => 'required_without:file|url'
    ]);

    if ($this->has('url') && $this->has('file')) {
        $validator->after(function (\Illuminate\Validation\Validator $validator) {
            $validator->errors()->add('url', 'error message');
        });
    }

    return $validator;
}

Upvotes: 1

Sapnesh Naik
Sapnesh Naik

Reputation: 11636

Your should use required_without:foo,bar,... see here

example

'author_id' => 'required_without:teacher_id',
'teacher_id' => 'required_without:author_id',

Upvotes: 2

Related Questions