phpmysqllaravelcodeignitereloquent

Laravel, how to run update on table column using old value


I have a table of users with encrypted (not hashed) passwords.

I want to update rows that are using a certain encryption (not all rows are using this encryption)

I need to use the old value for the password, decrypt it, and encrypt it using a new encryption.

 $result = DB::connection('writer')
             ->table('users')
             ->where('pw', 'LIKE', 'oldEncryption')
             ->get();

 foreach($result as $r){
        $password = olddecrypt($r->pw);
        $newpassword = newencrypt($password);
        $r->pw = $newpassword;
 }

 DB::connection('writer')
     ->table('users')
     ->update($result);

heres the non working "pseudo code" any good approach for this?


Solution

  • This should get you started in the right direction.

    $users = DB::connection('writer')
                  ->table('users')
                  ->where('pw', 'LIKE', 'oldEncryption')
                  ->get();
    
    foreach ($users as $user) {
        DB::connection('writer')
            ->table('users')
            ->where('id', $user->id)
            ->update(['pw' => newencrypt(olddecrypt($user->pw))]);
    }
    

    newencrypt and olddecrypt I'm assuming are your own implementations.