I am beginner in Laravel. I need validation to my project. I use Laravel 8. I have this code in TaskRequest:
public function rules()
{
return [
'speed_number' => ['required', 'string', 'min:3', 'max:255'],
'order_number' => ['required', 'string', 'min:3', 'max:255'],
'address_from' => ['required', 'string', 'min:3', 'max:255'],
'address_to' => ['required', 'string', 'min:3', 'max:255'],
'carrier_name' => ['required', 'string', 'min:3', 'max:255'],
'carrier_nip' => ['required', 'string', 'min:3', 'max:255'],
'carrier_street' => ['required', 'string', 'min:3', 'max:255'],
'carrier_email' => ['required', 'string', 'min:3', 'max:255'],
'carrier_phone' => ['required', 'string', 'min:3', 'max:255'],
'carrier_postal_code' => ['required', 'string', 'min:3', 'max:255'],
'carrier_city' => ['required', 'string', 'min:3', 'max:255'],
];
}
I need something like this:
public function rules()
{
return [
'speed_number' => ['required', 'string', 'min:3', 'max:255'],
'order_number' => ['required', 'string', 'min:3', 'max:255'],
'address_from' => ['required', 'string', 'min:3', 'max:255'],
'address_to' => ['required', 'string', 'min:3', 'max:255'],
if($company == true){
'carrier_name' => ['required', 'string', 'min:3', 'max:255'],
'carrier_nip' => ['required', 'string', 'min:3', 'max:255'],
'carrier_street' => ['required', 'string', 'min:3', 'max:255'],
'carrier_email' => ['required', 'string', 'min:3', 'max:255'],
'carrier_phone' => ['required', 'string', 'min:3', 'max:255'],
'carrier_postal_code' => ['required', 'string', 'min:3', 'max:255'],
'carrier_city' => ['required', 'string', 'min:3', 'max:255'],
}
];
}
(I need add if statement in request validation code). How can I make it?
Please help me :)
CodePudding user response:
Seems like you're looking for the required_if
rule. See the docs: https://laravel.com/docs/9.x/validation#rule-required-if
public function rules()
{
return [
'speed_number' => ['required', 'string', 'min:3', 'max:255'],
// ... and other rules ...
'carrier_name' => ['required_if:company,1', 'string', 'min:3', 'max:255'],
// ... and other rules ...
];
}
CodePudding user response:
You need use the Rule::requiredIf
use Illuminate\Validation\Rule;
'carrier_name' => [
Rule::requiredif(function () use ($company) {
return $company == true ? true : false;
}),
'string', 'min:3', 'max:255'
],
CodePudding user response:
Since from the question it's not clear if company
is in the request.
If it is not you could just return different values based on $company
public function rules() {
if ($company) {
// return rules for when company exists
} else {
// return rules for when company does not exist
}
}
If company is in the request, you should take a look at the required_if
validation Laravel provides. Laravel Docs - Required if