1

I'm using Laravel 5.1 and have created dynamic querying for filters.

I'm passing through the Model I'd like to query on, the filter fields (category_id, review, etc), and the values within those respective fields.

I'm passing in the field I'd like and getting its function TO BE run (don't run it yet):

$method = $this->getFilterForField($filter_field);

Then I'm calling the method with params:

$method($query, $filters_array, $user);

Query logger is telling me the queries are being run twice (see below).

How can I defer the method call until I actually want to run it with my params? Meaning, can I return a string representation of a method to be called at a later point?

I know in PHP you can wrap method names in Strings and call them later, as such:

$func = 'where'; 
$query->{$func('blah', 'foo')};

$func = 'in_array'; 
$func($needle, $haystack);

Or can use call_user_func as shown here, but this doesn't help me with how I should store and retrieve my methods.

Loop:

    $query = $model_class::query();
    foreach ($input as $filter_field => $filters_array) {

        //Get the method
        $method = $this->getFilterForField($filter_field);

        //Run method with params
        $method($query, $filters_array, $user);
        ...

Method:

public function getFilterForField($field)
{
    $filters = [
        'category_id' => function($query, $args, $user = null) {
            return $query->whereIn();
        },
        'review' => function($query, $args, $user = null) {
            if (in_array('yes', $args) && in_array('no', $args)) {
                return $query->orWhereHas();
            } else (in_array('yes', $args) && !in_array('no', $args)) {
                return $query->whereHas();
            }
        }
    ];

    return $filters[$field];
}

Query log if needed:

With $method = $this->getFilterForField($filter_field); AND $method($query, $filters_array, $user);:

enter image description here

Commented out the method call: $method($query, $filters_array, $user);

enter image description here

Community
  • 1
  • 1
user3871
  • 12,432
  • 33
  • 128
  • 268

0 Answers0