0

I make validation form which update user, and I have a problem. When I want to update only first name, show me validate error that email is already been taken, but I don't change email. So what can I do that not show validate error if I not change email ?

This is rules()

public function rules()
{
    return [
        'first_name'   => 'min:3|max:20|regex:/^[a-zA-z-0-9]+$/u',
        'last_name'    => 'string|min:3|max:30|regex:/^[a-zA-z-0-9]+$/u',
        'email'        => 'email|unique:customers,email',
        'phone_number' => 'min:9|max:9|unique:customers','phone_number'
    ];
}

view

<form action="{{ route('customers.update', ['customer' => $customer->id]) }}" method="POST" novalidate>

        <div class="form-outline mb-4">
            <input type="text" id="form4Example1" class="form-control" name="email"
                   value="{{ old('email', $customer->email) }}"/>
            <label class="form-label" for="form4Example1">Email</label>
            @error('email')
            <span class="text-danger">
                                        {{ $message }}
                                    </span>
            @enderror
        </div

controller

public function update(CustomerRequest $request, $id)
{
   Customer::updated($request->validated());

    return redirect()->route('customers.index')->with('updateMessage', 'Customer data successfully updated');
}
perh23
  • 29
  • 6
  • The unique rule has logic to ignore the current record when checking for Unique values: https://laravel.com/docs/9.x/validation#rule-unique – Tim Lewis Jan 13 '23 at 20:27
  • Also, you've got some errors: `'min:9|max:9|unique:customers','phone_number'` should be `'min:9|max:9|unique:customers,phone_number'`, and it's `Customer::update()`, not `Customer::updated()`. – Tim Lewis Jan 13 '23 at 20:30
  • @TimLewis I use `Rule::unique('customers')->ignoreModel($this->customer())` but show me error `Method App\Http\Requests\CustomerRequest::customer does not exist.` – perh23 Jan 13 '23 at 20:46
  • `$this->customer`, not `$this->customer()` – Tim Lewis Jan 13 '23 at 20:51
  • @TimLewis Now show me error `Call to a member function getKeyName() on string` – perh23 Jan 13 '23 at 21:03
  • Not sure, but if I had to guess, it has something to do with `update(CustomerRequest $request, $id)`. That _should_ be `update(CustomerRequest $request, Customer $customer)`. – Tim Lewis Jan 13 '23 at 21:05
  • If that doesn't work, please ask a new question with your updated code; don't keep posting new issues/errors in the comments. – Tim Lewis Jan 13 '23 at 21:05

0 Answers0