0

I have an active database with username columns but I later discovered it has a lot of whitespace which causes a not found error when I try to compare a record against itself. So I am trying to remove all white space from all user names, here is the challenge:

$user = (User::where("unique_id", 1)->first())->username;
    $string = preg_replace('/\s+/', '', $user);
   $dd = DB::table("users")->where("unique_id", 1)
   ->update(["username"=>$string]);

Where I select a single query like the above and change the the username it works,

but when I try to change the whole usernames in the database at once it does not work.

$user = User::all();
    foreach($user as $user){

        $username = preg_replace('/\s+/', '', $user->username);
        // $sponsor = preg_replace('/\s+/', '', $user->sponsor_username);
        DB::table("users")->where("unique_id", $user->id)->update(["username"=>$username]);
    }
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
M'Baku
  • 320
  • 4
  • 18
  • What _does_ happen? Are you getting an error? – Patrick Q May 18 '18 at 14:17
  • it just does not remove the whitespaces, when i go to the table and check the whitespace is still there – M'Baku May 18 '18 at 14:19
  • Try changing `$user = User::all();` to `$users = User::all();` and `foreach($user as $user){` to `foreach($users as $user){` – Patrick Q May 18 '18 at 14:21
  • 1
    Did the `update` show a row changed, and did the `preg_replace` actually change the value? Additionally if you are just talking about leading/trailing whitespace I'd use `trim`. You can do that from the db `update users set username = trim(username)`. – user3783243 May 18 '18 at 14:23
  • Okay I have seen the error, I was doing this `where("unique_id", $user->id)` instead of `where("unique_id", $user->unique_id)` – M'Baku May 18 '18 at 14:29

0 Answers0