J
J
jazzus2019-04-04 21:28:11
Laravel
jazzus, 2019-04-04 21:28:11

Why is there a Duplicate entry for key user_id_unique error?

Laravel 5.8, php 7.3, Mysql, Ubuntu
Error
Integrity constraint violation: 1062 Duplicate entry for key 'user_locations_user_id_unique' (SQL: insert into `user_locations` fields).
The error is only in production. Tests do not reproduce. Occurs sometimes for some users for unknown reasons. These users are no different from others. I watched the metric record - the user adds data without any problems. Makes only validator Form Request errors (does not fill in the required field), then fills in - the record is saved and the error is in the logs. I thought I fixed it via $request->except('id', 'user_id') But it appeared again in the logs (20 entries from one user, although I clicked save 2 times). The code

public function store(ContactRequest $request)
 {
       $user = Auth::user();
       $country = Country::find($request->input('country_id'));

       if (!$id = $request->input('id')) {
           $location = new UserLocation;
           $request['user_id'] = $user->id;
           $location=$location->create($request->all());
       }else{
           $location = UserLocation::findOrFail($id);
       }

       if (!$country->isOtherCountry()) {
            $request['other_country'] = null;
            $request['other_code'] = null;
       }

       if ($location->update($request->except('id', 'user_id'))) {
           return response()->json(['success_msg'=>'Адрес сохранен']);
       }
 }

Could this be related to the production server? Check what?
Update
Rewrote creation via user relation
$user->location()->create($request->all());

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question