4

I'm wondering if there is an eloquent method which I can pass the where method an array. For example

I have an array of query params like so:

[
    "limit" => "4"
    "is_completed" => "true"
    "status" => 1
]

So I can just pass in:

$this->model->whereArray($queryParams)->get();

and that whereArray method just loops through each query param and would do something similar to this:

foreach($queryParam as $param => $key)
{
    $this->where($param, '=', $key);

    return $this;
}

2 Answers 2

2

Yes, You can do the following.

$this->model->where([
    "limit" => "4",
    "is_completed" => "true",
    "status" => 1,
])->get();

Above will use and by default to join the wheres. If you need to override that behavior you can pass a fourth parameter.

$this->model->where([
    "limit" => "4",
    "is_completed" => "true",
    "status" => 1,
], null, null, 'or')->get();
Sign up to request clarification or add additional context in comments.

Comments

1

In my opinion I will use a query scope to make my codes more modular. In Eloquent's query scope provided you have a model, you will use

    public function scopeFilter($query) {
    $query->where('param1', 'operator', 'value1')
            ->where('param2', 'operator', 'value2')
            ->where('param3', 'operator', 'value3')
            ->where('param4', 'operator', 'value4');
}

After specifying the query scope in your model, you then call it just like a function in your controller.

$this->model->filter()->get();

And you are good to go. Don't forget to change the operator to something useful and the naming convention for the scope is Camel Case.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.