How can i avoid update a password in Laravel when the password input field is left empty?

Neyelson Alves :

I got this code in laravel that allows an administrator to update an user's password:

public function editarmembro(Request $dados)    {

        $validatedData = $dados->validate([

            'name' => 'required',
            'email' => 'required',
            'credencial' => 'required',

        ]);

        $dados = $dados->all();

        if (!empty($dados['password'])) {
            $dados['password'] = Hash::make($dados['password']);
        }

        DB::table('users')->where('id', $dados['id'])->update(
            [ 'name' => $dados['name'], 'email' => $dados['email'], 'credencial' => $dados['credencial'], 'password' => $dados['password'], 'sobre' => $dados['sobre'], 'updated_at' => Carbon::now(),  ]
        );

        return redirect()->route('membros')->with('mensagemSucesso',  'As informações do membro "'.$dados['name'].'" foram atualizadas com sucesso.');

    }

My problem is, if he left the password field blank, i get an error screen saying that the password field cannot be NULL. I want my code to NOT update the password if he left the password field blank, but DO update if he inserts something in password field.

Help, pls.

porloscerros Ψ :

You can remove it from the $dados array if it's empty:

if (!empty($dados['password'])) 
    $dados['password'] = Hash::make($dados['password']);
else 
    unset($dados['password']);

or with ternary operator

!empty($dados['password'])? $dados['password'] = Hash::make($dados['password']): unset($dados['password']);

and since all the names of the fields match those of the request and the updated_at field should auto-complete, you don't need to reassemble the array for the update.

DB::table('users')->where('id', $dados['id'])->update($dados);

If you want to reassemble the array anyway, you can do so

$update_dados = [ 
        'name' => $dados['name'], 
        'email' => $dados['email'], 
        'credencial' => $dados['credencial'], 
        'sobre' => $dados['sobre'], 
        'updated_at' => Carbon::now(),  
];

if (!empty($dados['password'])) 
    $update_dados['password'] = Hash::make($dados['password']);

DB::table('users')->where('id', $dados['id'])->update($update_dados);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=9740&siteId=1