Laravel foreach model

Viewed 191

I have some problems foreaching model for whereIn function. I want to foreach data that looks like this:

[
    {
        "product_id": "8614530b-2d6b-4750-941a-ef123105eaca",
        "product_name": "product1",
        "country_id": "c4c3d36b-e32c-4687-82ed-afdff7a17735",
        "country_name": "Greece"
    },
    {
        "product_id": "8614530b-2d6b-4750-941a-ef123105eaca",
        "product_name": "product1",
        "country_id": "c4c3d36b-e32c-4687-82ed-afdff7a17735",
        "country_name": "Hungary"
    },
    {
        "product_id": "2bee007f-ca28-410b-b4b4-779e7ef180b6",
        "product_name": "product2",
        "country_id": "7aa06799-f6fc-4837-9a0f-9821cd98e729",
        "country_name": "Hungary"
    },
    {
        "product_id": "2522e1f8-1bee-43ed-8e96-7bdb540dfeec",
        "product_name": "product3",
        "country_id": "7aa06799-f6fc-4837-9a0f-9821cd98e729",
        "country_name": "Hungary"
    }
]

So, I want to search orders for every each country and product, because product 1 is in 2 countries, and others have only 1 country, so they can't see order for that product in other countries. So I tried something like this:

    $products = UserAgent::getUserProducts(); // returns data 
    $orders = Orders::with('details.status', 'client', 'product', 'products');


        foreach ($products as $key => $permission){
             $orders->whereIn('product_name', $permission['product_name']);
             $orders->whereIn('country_id', $permission['country_id']);
        }


 return $orders->get();

and it always give's this error:

Argument 1 passed to Illuminate\Database\Query\Builder::cleanBindings() must be of the type array, string given

Any ideas how to fix that?

2 Answers

Since you use whereIn() you don't need to loop over the array. You only need to pluck() an array containing values of one column to pass it to whereIn()

$products = UserAgent::getUserProducts(); // returns data 
$orders = Orders::with('details.status', 'client', 'product', 'products')
    ->whereIn('product_name', Arr::pluck($products, 'product_name'))
    ->whereIn('country_id', Arr::pluck($products, 'country_id'));

return $orders->get();
foreach ($products as $key => $permission){
             $orders->whereIn('product_name', [$permission['product_name']]);
             $orders->whereIn('country_id', [$permission['country_id']]);
        }

2nd argument for whereIn must be an array

Related