Shiva
7 months ago

Getting multiple validations to work

Posted 7 months ago by Shiva

In my code I have multiple validations depending on where the user hits. The problem I'm having is that instead of this error showing There were validation errors I'm getting a list of the errors.

Here is the code

public function postPersonalDetails(Request $request)
    {
        $id = Auth::user()->id;

        $user = User::findOrFail($id);
        $existing_password = $user->password;
        $old_email = $user->email;

        if(empty($request->input('existing_password')))
        {
            $password = $existing_password;
        }else{
            if(Hash::check($request->existing_password, $existing_password))
            {
                $password = Hash::make($request->password);
                $request->validate($this->getNewPasswordRule());
            }else{
                return redirect()->back()->with('error', 'Your existing password does not match.');
            }
        }

        if($request->input('email') == $old_email)
        {
            $email = $old_email;

            $old_email_validation = Validator::make($email, $this->getNewEmailRule());

            if($old_email_validation->fails())
            {
                return redirect()->route('account.details')
                                ->withErrors($validation)
                                ->with('error', 'There were validation errors');
            }
        }else{
            $email = $request->email;
            $email_validation = Validator::make($email, $this->getNewEmailRule());

            if($email_validation->fails())
            {
                return redirect()->route('account.details')
                                ->withErrors($validation)
                                ->with('error', 'There were validation errors');
            }
        }


        $validation = Validator::make($request->all(), $this->getRules());

        if($validation->fails())
        {
            return redirect()->route('account.details')
                            ->withErrors($validation)
                            ->with('error', 'There were validation errors');
        }

        $user->email = $email;
        $user->password = $password;
        $user->salutation = $request->salutation;

        $user->name = $request->name;
        $user->surname = $request->surname;
        $user->phone_number = $request->phone_number;
        $user->telephone_2 = $request->telephone_2;
        $user->save();

        return redirect()->route('account.details')->with('success', 'Details saved successfully');
    }

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