S
S
sugarufc2021-02-03 12:31:38
Laravel
sugarufc, 2021-02-03 12:31:38

How to overwrite a record in the database if the record already exists?

There is a list of employees. Each has a unique IP address.
601a6b7ec3db0774963611.png
601a6b8d5d237232574406.png

When editing an employee (for example, changing the name or phone number), the record is not saved, indicating that such an ip already exists (although the ip has not been changed and it is unique in the database), and I just need to resave the same ip address
601a6c526437e992965434.png

here is the action that handles saving records in the database

public function update(Request $request, $id){
        $rules = [
            'vts' => 'numeric|nullable',
            'gts' => 'numeric|nullable',
            'mobile' => 'numeric|nullable',
            'ip_wks' => 'unique:workers|nullable',
            'ip_int' => 'unique:workers|nullable'
        ];

        $messages = [
            'vts.numeric' => 'Поле должно содержать только цифры',
            'gts.numeric' => 'Поле должно содержать только цифры',
            'mobile.numeric' => 'Поле должно содержать только цифры',
            'ip_wks.unique' => 'IP адрес уже существует',
            'ip_int.unique' => 'IP адрес уже существует',
        ];

        $validateData = Validator::make($request->all(), $rules, $messages)->validate();

        $worker = Worker::find($id);
        $worker->update($request->all());
        return redirect(session('links')[2])->with('success', 'Данные успешно сохранены');
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Anton, 2021-02-03
@sugarufc

Something like

use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
///////
Validator::make($data, [
            'vts' => 'numeric|nullable',
            'gts' => 'numeric|nullable',
            'mobile' => 'numeric|nullable',
            'ip_wks' => Rule::unique('workers')->ignore($id)->nullable(),
            'ip_int' => Rule::unique('workers')->ignore($id)->nullable()
]);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question