J
J
Jedi2020-12-13 04:16:25
Laravel
Jedi, 2020-12-13 04:16:25

Have I implemented the method correctly?

Guys, did I implement the correct method to change the user's password? The code looks like this to me.

/**
     * Change the user password.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function changePassword(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'current_password' => [
                'required',
                'string',
                function ($attribute, $value, $fail) {
                    if (! Hash::check($value, Auth::user()->getAuthPassword())) {
                        $fail('The '.$attribute.' is invalid.');
                    }
                },
            ],
            'new_password' => 'required|string|min:8|confirmed'
        ]);

        if ($validator->fails()) {
            return response()->json($validator->errors()->getMessages(), 422);
        }


        $user = Auth::user();

        $user->password = Hash::make($request->new_password);
        $user->save();

         // Не важно что возвращаем, это я потом поменяю. 
        return response()->json($user);
    }


How would you accomplish this task? I don't like how I implemented the validator, for example. The point is not in the written function, but in the fact that it seems to me - crutches. Even if you separately create Rule. Correct, please. I want to know your opinion.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jazzus, 2020-12-13
@PHPjedi

I would put it in a request, which 422 will give automatically. And for current_password there is a password rule and you can also add different

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question