In Laravel, you can easily compare two column using simple whereColumn
in query builder.
If you need to get all records from table where value of two columns are equal then you can easily get it in Laravel by using whereColumn.
There may be so many condition where you can use this method with comparison operator.
You can also pass an array of multiple conditions in this method but make sure all conditions passed within array will be joined using and operator.
Example 1:In this example, we will get all products where price of both column (column main_price and offer_price) will be equal.
- $products = DB::table('products')
- ->whereColumn('offer_price', 'main_price')
- ->get();
In this example, we will get all products where price of column main_price will be higher than column offer_price.
- $products = DB::table('products')
- ->whereColumn('main_price', '>', 'offer_price')
- ->get();
In this example, we will pass multiple condition in array.
- $products = DB::table('products')
- ->whereColumn([
- ['offer_price', '=', 'main_price'],
- ['updated_at', '>', 'created_at']
- ])->get();