Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

aneeshrp's avatar

Reusing query with extra where condition.

I wanted to create two separate data sets from same table with two different condition.

For e.g see below, this is what all I need.

$filter = "select * from filters"; $filter_one = $filter . " where filtername = 'test'; $filter_two = $filter . " where filtername = 'test1';

I did it in the following way using laravel.

$filter = \App\DailyTracker::query(); $filter_one = $filter; $filter_two = $filter;

$res1 = $filter_one->where('filtername', 'test')->get(); $res2 = $filter_two->where('filtername', 'test1')->get();

$res1 gets the record as I expected, however $res2 is null because the second condition appended to the first one.

I guess it is object reference and that may be the reason. Anyhow, is there any way to achieve my requirement so that I can avoid writing same line of code again and again.

0 likes
7 replies
frezno's avatar

@aneeshrp

one solution could be to write a helper function, eg like so:

public function filterMyDailyTracker($filtername)
{
    $filter = \App\DailyTracker::query()->where('filtername', $filtername)->get();

    return $filter;
}
1 like
acasar's avatar
acasar
Best Answer
Level 13

@EliasSoares That won't work since newQuery creates an empty query.

The best way to solve it is as @frezno suggested, or clone the query manually:

$filterOne = clone $filter; 
$filterTwo = clone $filter;
4 likes
EliasSoares's avatar

@acasar Yes, sorry, I did some tests that worked, but it does not clone it.

The PHP clone solves it as you said.

2 likes
aneeshrp's avatar

@EliasSoares Thank you for your reply. I applied your solution, but it is making a new query, not a continuation of the object we are attempting to modify. Once again thanking you for the suggestion.

aneeshrp's avatar

@frezno I didn't check your suggestion, as @acasar 's solution worked for me. But thanks alot for your time and consideration.

Please or to participate in this conversation.