Validation rule for unique on 2 fields? See this code example which checks to see if fulfillment_tracking_number on the order_fulfillments table is unique.
// Validate against duplicate fulfillment_tracking_number
$rules = [
'fulfillment_tracking_number' => 'required|unique:order_fulfillments,fulfillment_tracking_number',
];
$validator = Validator::make($request->all(), $rules);
if($validator->fails()) {
return response()->json($validator->errors(), 403);
}
I want to also check if the fulfillment_freight_company is the same in the same validation rule, how do I do that with Laravel Validation rules?
You need one for each
$rules = [
'fulfillment_tracking_number' => 'required|unique:order_fulfillments,fulfillment_tracking_number',
'fulfillment_freight_company' => 'required|unique:order_fulfillments,fulfillment_freight_company',
];
Or build you own
$rules = [
'fulfillment_tracking_number' => [Rule::unique('order_fulfillments')->where(function ($query) use ($request) {
return $query->where('fulfillment_tracking_number', $request->input('fulfillment_tracking_number'))->where('fulfillment_freight_company', $request->input('fulfillment_freight_company'));
}),]
@sinnbeck not quite..
That would mean its checking for fulfillment_freight_company has to be unique.
For an online eCommerce store...
An order can be sent by multiple fulfillment_freight_company (s)...
However, for example:
fulfillment_freight_company (1)
tracking_number: 123456
fulfillment_freight_company (2)
tracking_number: 123456
that is fine...
However,
fulfillment_freight_company (1)
tracking_number: 123456
fulfillment_freight_company (1)
tracking_number: 123456
That is not fine.
Did you try my second example?
I'm using Laravel 6. I get this error message...
{
"message": "Call to undefined method Illuminate\Contracts\Validation\Rule::unique()",
"exception": "Symfony\Component\Debug\Exception\FatalThrowableError",
You have the wrong import at the top. It should be
use Illuminate\Validation\Rule;
@sinnbeck
2nd example works...
// Validate against duplicate fulfillment_tracking_number + FulfillmentCompany
// fulfillment_freight_company is a string so it has to be exactly the same to throw a validation error
$rules = [
'fulfillment_tracking_number' => [Rule::unique('order_fulfillments')->where(function ($query) use ($request) {
return $query->where('fulfillment_tracking_number', $request->input('fulfillment_tracking_number'))->where('fulfillment_freight_company', $request->input('fulfillment_freight_company'));
}),]
];
Please sign in or create an account to participate in this conversation.