The Problem
I'm working on Invoice Lines. When the line type is 'Text Only' the price and quantity fields should be blank.
When the line type is 'Item' the price and quantity fields are required.
What Laravel already does:
The required_if function works perfectly for saying "OK it's an item line, require the quantity and price.
What I need:
A function which works similarly but expects the field to be empty, preventing users from putting prices and quantities against text-only lines.
How I am using the rules:
class StoreInvoiceRequestDetail extends FormRequest
{
public function rules()
{
return [
'type_id' => 'required|integer|exists:invoice_request_detail_types,id',
'item_price' => [
'nullable',
'numeric',
'empty_if:type_id,'.InvoiceRequestDetailType::TEXT_ONLY.',Line Type,Text Only',
'required_if:type_id,'.InvoiceRequestDetailType::ITEM.'Line Type,Item',
],
'item_quantity' => [
'nullable',
'numeric',
'empty_if:type_id,'.InvoiceRequestDetailType::TEXT_ONLY.',Line Type,Text Only',
'required_if:type_id,'.InvoiceRequestDetailType::ITEM.',Line Type,Item',
],
'description' => 'required|string|min:3|max:'.ApplicationConstant::STRING_LONG,
'invoice_request_id' => 'required|integer|exists:invoice_requests,id',
];
}
}
This works:
Usage
Extenders
Validator Lang
I've added field name and value alias options in the replacers for ease of use, however technically I should have probably just called my field
invoice_request_line_type_idinstead of justtype_id. The values lang isn't really going to work for me in this instance which is a trap, because it won't get translated, but you could insert those values from Lang into the validator anyway.