Laravel Eloquent- Where Condition with Two Columns

0
5

Did you ever think about how to write where condition with two columns(fields) in Laravel Eloquent? In the first place, this is possible in Laravel using the function whereColumn.

For example, you have two fields named sub_total and grand_total, and you need to find all the orders have the same sub_total as grand_total.

So you can use the whereColumn to get the desired results.

Example 1

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
 public function index()
 
    $orders = Order::whereColumn('sub_total','grand_total')
                ->get();
    dd($orders);

Example 2

Also, you can use a comparison operator with this method, the same as the where method.

public function index()

    $orders = Order::whereColumn('updated_at', '<', 'created_at')
                ->get();
    dd($orders);

Example 3

The whereColumn method can also be passed an array of multiple conditions. The multiple parameters will be joined with an and operator.

/**
 * Example for whereColumn
 *
 * @var array
 */
 public function index()
 
    $orders = Order::whereColumn([
                    ['sub_total', '=', 'grand_total'],
                    ['created_at', '<', 'updated_at'],
                ])->get();
    dd($orders);
 

Editorial Staff

Editorial Staff at Tutsplanet is a dedicated team to write various tutorials about subjects like Programming, Technology and Operating Systems.

Source

LEAVE A REPLY

Please enter your comment!
Please enter your name here