4 months ago

Validator fails on PUT request

Posted 4 months ago by Romentigo

I have the next method in my controller:

public function update(Request $request, $id)
        $validator = Validator::make($request->all(), [
            'last_name' => ['required', 'string', 'min:2', 'max:20'],
            'first_name' => ['required', 'string', 'min:2', 'max:20'],
            'middle_name' => ['required', 'string', 'min:2', 'max:20'],
            'email' => ['email', 'max:255', 'unique:users', 'unique:students', 'unique:lecturers', 'nullable'],
            'phone' => ['required', 'string', 'size:18', 'unique:lecturers', 'unique:students'],
            'degree_id' => ['required', 'integer'],
            'department_id' => ['required', 'integer']
        ], $this->messages());

        if ($validator->fails())
            return response()->json($validator->messages())->setStatusCode(422);

        $compare = Lecturer::where('last_name', '=', $request->last_name)
            ->where('first_name', '=', $request->first_name)
            ->where('middle_name', '=', $request->middle_name)

        if (!$compare->isEmpty())
            return response()->json(['message' => 'Такий викладач вже існує!'])->setStatusCode(500);
        else {

            return response()->json(['message' => 'Викладач був оновлений!'])->setStatusCode(200);

So, validator checks if everything is ok, then I'm looking for existing last name, first name and middle name. If it's empty, it's allowed to update the record.

But I have a problem with validator. When I send a PUT request, validator fails. For example, I just editing first name, other fields stay the same, but on PUT request it says, that such email and phone number already exist, but they belong to person I edit at the moment, no other people have such values. How can I solve it?

Please sign in or create an account to participate in this conversation.