phplaraveleloquent

Laravel eloquent where replace and compare


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

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.


Solution

  • 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.