Home » Php » php – How can i avoid update a password in Laravel when the password input field is left empty?

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

Posted by: admin February 25, 2020 Leave a comment

Questions:

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.

How to&Answers:

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);

Answer:

You just need to merge to the array with all the values (except the password) the password only if exists / is set:

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