Error editing an entity with a unique Laravel field

2

I have an entity activities with the following Form Request as indicated in the documentation

public function rules()
{
    return [
        'name' => "required|max:200|unique:activities,name,". $this->activity_id
    ];
}

When editing, send the data by axios:

    $("#frmEditActivity").submit(function (e) {
                e.preventDefault();

                axios.patch("/admin/actividades/" + $("#frmEditActivity #activity_id").val(), $(this).serialize())
                    .then(function (response) {
                        self.loadTable();
                        toastr.success(response.data);
                        $("#mdlEdit").modal('hide');
                    })
                    .catch(function (error) {
                        error.response.status == 422 ? toastr.error(error.response.data.errors.name) : "Ocurrió un error. Intentelo de nuevo!";
                    });
            });

and when sending the data I receive the following error:

  

SQLSTATE [23000]: Integrity constraint violation: 1062 Duplicate entry   'xxx' for key 'activities_name_unique

The route is:

 Route::resource('actividades', 'ActivityController', [
    'except' => 'create', 'edit', 'show',
    'names' => 'activities'
]);

The driver is:

   public function update(ActivityRequest $request, ActivityModel $activity)
    {
        if ($request->ajax()) {

            if ($this->activityRepo->edit($request->all(), $activity)) {
                return response()->json('Actividad editada correctamente.');
            }

            return response()->json('Ocurrió un error. Por favor inténtelo nuevamente!');
        }

        return redirect(route('admin.activities.index'));
    }
    
asked by Juan Pablo B 24.11.2018 в 00:51
source

1 answer

0

The error is that it tries to access a field ( $this->activity_id ) within the FormRequest that does not exist.

By using Route model binding you have access to model object ActivityModel from this object, the attribute would be accessed to validate that it does not take into account the value of activity_id for the restriction UNIQUE

return [
    'name' => "required|max:200|unique:activities,name,". $this->activity->activity_id
];

If the primary key would have the name id , it would be

return [
    'name' => "required|max:200|unique:activities,name,". $this->activity->id
];
    
answered by 24.11.2018 в 01:50