Nurideen Yahuza
Nurideen Yahuza

Reputation: 43

Laravel - How to update query by transforming existing column value

I have a table of users with column phone_number. I want to update the table by keeping the last 9 characters of the existing values.

This is the query I'm using and it doesnt work for me.

$user = User::where('usertype','=',1)->get(); $user->update(['phone_number' => substr($user['phone_number'],-9)]);

I get the error "Undefined array key "phone_number"

Upvotes: 2

Views: 1908

Answers (1)

N69S
N69S

Reputation: 17206

you can do it on the database without getting the data.

$numberOfAffectedRows = User::where('usertype','=',1)->update(['phone_number' => \DB::raw("SUBSTRING('phone_number',-9)")]);

Upvotes: 5

Related Questions