I want to add conditional validation to my request. I have different user roles and different fields for some users.
I want to check if the user role is business then some fields are required and if the user is a worker then business user fields are not required.
$this->validate($this->_request, [
'name' => 'required',
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'phone' => ['required', 'max:22'],
'municipality_of_origin' => 'required',
]);
These are required for all users. Now I want to check if a user is business
if($role == 'business'){
'company_name' => 'required',
'company_title' => 'required',
}
if($role == 'worker'){
'designation' => 'required',
'salary' => 'required',
}
$data = $request->safe()->only('name', 'email', 'phone', 'municipality_of_origin');
$user = User::create($data);
if($role == 'business){
$business_user = $request->safe()->only('company_name', 'company_title');
$business_user['user_id'] = $user->id;
// business is hasOne relationship with User model.
$user->business->create($business_user);
}
Is there any best way to handle this type of conditional validation in laravel? I'm using Laravel 9.
I try Form validation but don't understand how to use FormRequest for this type of validation.
$rules = [];
$rules['name'] = 'required';
$rules['email'] = ['required', 'string', 'email', 'max:255', 'unique:users'];
$rules['phone'] = ['required', 'max:22'];
$rules['municipality_of_origin'] = 'required';
if ($this->attributes->has('some-key')) {
$rules['other-key'] = 'required|unique|etc';
}
and problem is $this->attributes->has() method return null all the time.