Laravel 5 get all records from table where two columns are equal

Laravel 5 get all records from table where two columns are equal

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.

  1. $products = DB::table('products')
  2. ->whereColumn('offer_price', 'main_price')
  3. ->get();
Example 2:

In this example, we will get all products where price of column main_price will be higher than column offer_price.

  1. $products = DB::table('products')
  2. ->whereColumn('main_price', '>', 'offer_price')
  3. ->get();
Example 3:

In this example, we will pass multiple condition in array.

  1. $products = DB::table('products')
  2. ->whereColumn([
  3. ['offer_price', '=', 'main_price'],
  4. ['updated_at', '>', 'created_at']
  5. ])->get();

Phone: (+91) 8800417876
Noida, 201301