简体   繁体   中英

Laravel eloquent where replace and compare

I've a phone number column in the users table. The phone numbers are in different formats:

  • 123-456-7890
  • (123) 456 7890

    etc...

I would like to compare by removing the extra characters and retrieve the results.

Here is the mysql query :

SELECT * FROM users WHERE REPLACE(REPLACE(REPLACE(`phonenumber`, '-', ''), '(', ''), ')', '') = '1234567890'

How can do I this in the Laravel Eloquent?

I know the best option would be to force the formatting on the DB column. I'm wondering if we can do this with Laravel Eloquent.

It's not going to be database-agnostic, but:

$query->whereRaw('REPLACE(REPLACE(REPLACE(`phonenumber`, '-', ''), '(', ''), ')', '') = ?', [$phoneNumber]);

See Raw Methods at https://laravel.com/docs/5.7/queries#raw-expressions


The better approach would be to remove these characters before inserting the numbers into the database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM