Laravel query builder - re-use query with amended where statement
The suggestion from @lukasgeiter using clone is definitely the way to go; the reason is that an Eloquent\Builder object contains an internal reference to a Query\Builder that needs to be duplicated.
To keep the flow of your app and get back to a more functional style, you can use Laravel's with()
helper, which simply returns the object passed in:
$result1 = with(clone $this->data_qry)->where('from', $from1)->where('to', $to1)->get();
$result2 = with(clone $this->data_qry)->where('from', $from2)->where('to', $to2)->get();
You can use clone
to duplicate the query and then run it with different where statements. First, build the query without the from-to constraints, then do something like this:
$query1 = $this->data_qry;
$query2 = clone $query1;
$result1 = $query1->where('from', $from1)->where('to', $to1)->get();
$result2 = $query2->where('from', $from2)->where('to', $to2)->get();
For the people who want a simpler and shorter syntax, you can daisy chain the clone()
method on the query builder.
$result1 = $this->data_qry->clone()->where('from', $from1)->where('to', $to1)->get();
$result2 = $this->data_qry->clone()->where('from', $from2)->where('to', $to2)->get();