Laravel Eloquent provides endless methods to query your database and make good collections.
But if you need to have normal MySQL expression in Laravel eloquent, such as replace white spaces from a field when using the where condition.
This will help to push some of the limits that are with the Eloquent in Laravel.
You can use the whereRaw() for this instance.
For example, I need to get the count of a mobile number existing in the database. But we have a situation here as some of the mobile numbers were entered previously with spaces and some of them are without spaces. In the first place, we need to remove the spaces for both input and database records before comparison takes place.
Basically, there are two methods you can use to
Using whereRaw()
$count = Customer::whereRaw("REPLACE(phone,' ', '') = '+1 98 90 891223'") ->count(); dd($count);
However, there is an alternate solution for this using the DB::raw() which will produce the same result as above.
Using DB::raw()
$count = Customer::where(DB::raw("REPLACE(phone,' ', '') = '+1 98 90 891223'")) ->count();
- Just want to thank us? Buy us a Coffee
- May be another day? Shop on Amazon using our links.
Your prices won't change but we get a small commission.
Leave a Reply