adamnet's avatar

Update a customer's code which was initially given wrong

Hello to everyone. In my customers table the user can define a customer code which must be unique. In the StoreCustomer request I have set the following rule:

'custcode' => 'required|max:5|min:5|unique:customers,custcode',

In case the user wants to correct the customer code, in the UpdateCustomer request I have the same rule:

'custcode' => 'required|max:5|min:5|unique:customers,custcode',

The problem arises when the user wants to update i.e. only a customer's address. Then I have the error message "this customer code already exists in this table". Given that the change of a wrong customer code must always be allowed, how can I overcome this problem? The customer code must be unique ok sure. But if I want to change a wrong accidentally given code, what is the correct way to do this? Also if the useer has the purpose to change something else, he facces this message for the customer code. Thank you Panagiotis

0 likes
3 replies
imrandevbd's avatar

If your route parameter name is different (like {id}), just change $this->route('customer') to match whatever is in your route:list. This way, Laravel checks for uniqueness across the whole table except for the row you are currently editing, allowing you to change the address without touching the code, or update the code to something brand new.

adamnet's avatar

For everyone looking for the correct code in the problem, here it is the solution:

 public function rules(): array
    {
        return [
           'customercode' => 'required|max:5|min:5',
           Rule::unique('customers')->ignore($this->customer)
        ];
    }

The code is working very well.

Please or to participate in this conversation.