In Laravel 10, How to make a rule or validation for this condition.
I have two inputs: order_number and part_number, we can have the same order_number but different part_number, for example:
order_number = 123, part_number = aba
order_number = 123, part_number = cddd
order_number = 123, part_number = fff
but order_number = 123, part_number = fff
is not accepted because with this order_number = 123 is exists already part_number = fff.
An even cleaner approach is to add unique:table_name
to your validation string.
for instance if you want to make sure that the part_number doesn't exist in the orders database, you may do the following:
'part_number' => 'unique:orders'
in case you're field name on the frontend doesn't match the column name in the backend you may specify that as well.
'part_number' => 'unique:orders,partNumber'
You need to manually add an item to the Laravel error bag only if a DB check is met:
if(Orders::where('part', $this->part_number)->count() > 0)
{
$validator->getMessageBag()->add('part_number', 'Part number already exists');
}
depending on your livewire setup, this may also work:
if(Orders::where('part', $this->part_number)->count() > 0)
{
$this->addError([key], [message]) // Replace key and message with your own key and message
}
More info on the topic can also be found here.