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

Ligonsker's avatar

How can I add query to an existing query from a variable?

Hello,

If I have a function with the base query, and I want to pass extra query as a variable:

function updateQuery($extra_query)
{
    $base_query = Model::where(...);
    // $base_query->(add $extra_query)->get();
}

For example if I want to add where('col_x', '=', $val) and pass that to the function, how can I do that?

Thanks

0 likes
3 replies
jlrdw's avatar

A scope would do this.

1 like
Ligonsker's avatar

@jlrdw thanks, will scopes also work if I user DB::table('table') instead of Model?

jlrdw's avatar

@Ligonsker even though Scopes are meant to be used a certain way, it's undocumented but you can return really anything from a scope, test it you can return hello world if you want to.

In other words you can use them outside of their intended purpose and it doesn't hurt anything.

1 like

Please or to participate in this conversation.