I am posting an JSON array to Slim. And with this array I would like to query the database. The issue is that I would like to make it more dynamic.
For now there are two columns to filter upon: ‘activity’ and ‘country’. I use Eloquent btw.
When I recieve to code my controller. It looks like this:
$data = $request->getParams();
$query = $data[‘activity’][0]; // first record of array
$querytwo = $data[‘activity’][1]; // second record of array
$querythree = $data[‘country’][0]; // first record of array
Then I use:
$products = Product::where(‘active’, true)
->whereIn(‘activity’, [ $query, $querytwo ])
->whereIn(‘country’, [ $querythree ])
->get();
So as you can see not really dynamic. In a procedural way you could use something like:
$query .= ', ’ . $querytwo;
SELECT * FROM table WHERE $query AND $querytwo;
I have used all kinds of methods (string implode, for, foreachloops etc.) - none of it seems to work. What would be a good approach for looping trough the array and executing the DB-call?
Check if $data[‘activity’] and $data[‘country’] are both arrays containing strings. If, for example, $data[‘country’] is a string instead of an array, PHP will issue a warning because it can’t iterate over a string using foreach.
The dynamic version you added will then work too. You probably want to place the first foreach outside the $queryBuilder->where() statement, or you end up with all conditions ORed. e.g.
$queryBuilder = Product::where('active', 1);
foreach ($data as $key => $value) {
// make sure $value is an array!
$queryBuilder->where(function($query) use ($data, $key, $value) {
foreach ($value as $item) {
$query->orWhere($key, '=', $item);
}
});
}
$products = $queryBuilder->get();