Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

HFH's avatar
Level 1

L5.5 Form Validation: Exclude password from user info update if empty string

Tried to be self-explanatory in the title.

Currently using Laravel 5.5

I have a basic user update form with the name, email, password and password confirmation present.

Here is the current validation and submission:

    // Validate the request data
        $this->validate($request, [
            'name' => 'required',
            'email' => 'unique:users,email,'.Auth::user()->id.'|required|email',
            'password' => 'nullable|string|min:6|confirmed'
        ]);

        // Update the user profile in the database
        Auth::user()->update($request->all());

    // This is where an integrity constraint violation gets thrown, because the database can't save a null password
        

The problem I run into is that I never want null to be passed to the database. Basically, if the user wants to only update their name/email and not their password, they can do so.

0 likes
2 replies
Snapey's avatar
Snapey
Best Answer
Level 122

as per the other answer, just treat password on its own;

    $this->validate($request, [
            'name' => 'required',
            'email' => 'unique:users,email,'.Auth::user()->id.'|required|email',
            'password' => 'nullable|string|min:6|confirmed'
    ]);

    // Update the user profile in the database
       $user = Auth::user();        //get instance of model

    $user->name = $request->name;           //set name on model
    $user->email = $request->email;         //set email on model

    //set the password ONLY if one was provided
    
    if(isset($request->password)) {
        $user->password = $request->password);   //probably need to hash it here
    }

    $user->save();

Please or to participate in this conversation.