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.
/** * 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); }
- 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