Reputation: 1952
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
Reputation: 101
Here are mention 2 different ways to do conditional validation e.g. Login functionality need fcmToken required if deviceType is "android"
public function login(Request $request){
// Validate fcmToken required if deviceType exist and androidif($request->has('deviceType') && $request['deviceType'] == "android") {
$request->validate([ 'fcmToken' => 'required',
);
} }
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
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
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