glasstree
glasstree

Reputation: 257

Laravel method chaining a query through a function

Is it possible to conditionally chain methods in PHP / Laravel, or to pass method chains through functions?

I'd like to control a query in Laravel's query builder by setting up a base query first, then passing that to a function to have other methods chained on to the query. As a quick example:

$query = Model::whereFoo('bar');

if ($needFoo) {
    $query = $query->has('foo');
}

$query = queryMethod($query);

function queryMethod($query) {
    return $query->where('something', '<', 10);
}

$items = $query->get();

This seems to ignore everything between $query = Model::whereFoo('bar'); and $items = $query->get(); -- it doesn't seem to make any difference what happens to $query in between the two.

Is it possible / advisable to achieve this?

Edit: I've accepted the answer below as it answers the question I asked. My problem was actually unrelated. If it helps anyone: I had a rogue orWhere() call in the base query that was of course including unwanted results regardless of the other chained methods. That needed nesting inside an advanced where method as described in Laravel docs.

Upvotes: 0

Views: 2629

Answers (1)

Joseph Silber
Joseph Silber

Reputation: 219920

What you have should work, but you can simplify it:

$query = Model::whereFoo('bar');

if ($needFoo) $query->has('foo');

queryMethod($query);

function queryMethod($query) {
    $query->where('something', '<', 10);
}

$items = $query->get();

Since objects in PHP are passed by reference, you'll always be dealing with the same instance.

Upvotes: 2

Related Questions