0

I have a repository function that gets data by using:

public function get($request){

    return User::where($request)->get();    

}

where the $request array is dynamic. The above works well as long as I pass in regular key value pairs:

$request = array(
    'name' => 'mike',
    'age' => 45
);

The above translates to this SQL:

SELECT * 
FROM users
WHERE name = 'mike' AND age = 45;

Every once in a while, I would like to pass in an array as one of the properties for $request:

$request = array(
    'name' => 'mike',
    'age' => array(45, 46)
)

and have it translate into the following SQL:

SELECT *
FROM users
WHERE name = 'mike' AND age IN(45, 46);

Any properties set as an array in $request should be treated as a where in statement as opposed to a vanilla where statement.

How would I do this?

3 Answers 3

1

This should handle it nicely...

public function get($request)
{
    $query = User::query();
    foreach ($request as $key => $value) {
        if (is_array($value)) {
            $query->whereIn($key, $value);
        } else {
            $query->where($key, $value);
        }
    }

    return $query->get();
}
Sign up to request clarification or add additional context in comments.

2 Comments

newQuery() isn't a static method. Anyway to do this without instantiating a new instance of my model?
Just use query() instead of newQuery().
0

You need to use the whereIn statement, something like:

User::where(['name' => 'jhon'])->whereIn(['age' => [45, 46])->get();

Comments

0

Check out the when() method https://laravel.com/docs/master/queries#conditional-clauses

In your case it would be:

public function get($request)
{
    $query = User::newQuery();

    foreach ($request as $key => $value) {
        $query->when(is_array($value), function($query)
        {
            return $query->whereIn($key, $value);
        }, function($query) use($key, $value)
        {
            return $query->where($key, $value);
        });
    }

    return $query->get();
}

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.