Andrew Fox
Andrew Fox

Reputation: 890

How to perform validation when updating a unique field using Http\Request in Laravel

I have a customers table that I use a CustomerRequest to validate the fields, through the use of the rules function. The table has an email field which is required and is unique. This works fine when I create the customer, however when I update the customer info (let's say I got their last name spelled wrong) my request fails because the email address is already in the database.

Here is my CustomerRequest:

public function rules()
{
    return [
        'givenname' => 'required',
        'surname' => 'required',
        'email' => 'required|unique:customers,email',
    ];
}

I would like to reuse the CustomerRequest for all of the customer vaildation, how can I go about doing this?

Upvotes: 2

Views: 96

Answers (1)

Niklesh Raut
Niklesh Raut

Reputation: 34924

You need to check here for request type as well as customer id for update and then return rules according to request. Something like this

public function rules(Request $customer_request)
{
return [
    'givenname' => 'required',
    'surname' => 'required',
    'email' => 'required|unique:customers,email,'.$customer_request->get('customer_id'),
];
}

Upvotes: 1

Related Questions