Laravel whereArray method

I'm wondering if there is an eloquent method that I can pass to the where method in an array. for example

I have an array of request parameters, for example:

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

      

So, I can just go through:

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

and that the method whereArray

just loops through each request parameter and does something similar to this:

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

    return $this;
}

      

+3


source to share


2 answers


Yes, you can do the following.

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

      



The above will use and

the default to join wheres

. If you need to override this behavior, you can pass a fourth parameter.

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

      

+1


source


In my opinion, I will use the query scope to make my codes more modular. In the scope of an Eloquent query, if you have a model, you would use

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

      

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



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

      

And you're good to go. Remember to change the operator to something useful and the naming convention for the Camel Case scope .

+1


source







All Articles