Date:

Share:

Laravel db raw and whereRaw() where clause example

Related Articles

Laravel Eloquent provides endless methods for querying your database and creating good collections.

But if you have to Standard MySQL expression In eloquent Laravel, such as replacing white spaces from a field when using where conditions.

This will help push some of the boundaries that exist with the Alcon Belravel.

You can use whereRaw () For this case.

For example, I need to get the count of an existing mobile number in the database. But we have a situation here where some of the mobile numbers have been entered in the past with spaces and some without spaces. To begin with, we need to remove the gains for both the input records and the database records before the comparison.

Basically, there are two methods you can use

Using whereRaw ()

$count = Customer::whereRaw("REPLACE(phone,' ', '') = '+1 98 90 891223'")
            ->count();

dd($count);

However, there is an alternative solution to this using the DB :: raw () Which will yield the same result as above.

Using DB :: raw ()

$count = Customer::where(DB::raw("REPLACE(phone,' ', '') = '+1 98 90 891223'"))
            ->count();

System staff

The editorial team at Tutsplanet is a dedicated team for writing various tutorials on topics such as programming, technology and operating systems.

Source

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Popular Articles