phparrayslaravellaravel-4

Using array values to select database table in laravel


I have this sorted array with top 5 products

foreach ($bestsellers as $item) {
      $data = json_decode($item->order_details, true);
      $product_ids[] = key($data);
}
      arsort($product_ids);
      $three = array_unique(array_slice($product_ids, 0, 5, true));
      print_r($three);

The result is

Array
(
    [0] => 1 
    [1] => 2 
    [2] => 3 
    [3] => 4 
    [4] => 5
)

1,2,3,4,5 are products id's. Is it possible to use this values in the query to products table so I can display on page more information about the products. Not just the ID.

Something like

Product::where('product_id', $value);

Update

$best = Product::whereIn('product_id', $three)->get();

foreach($best as $info)
{
    dd($info->title);
}

Solution

  • Yes, You should use whereIn for array. In fact, whereIn takes second parameter as array of values for specified column.

    Product::whereIn('product_id', $value);
    

    whereIn()

    The whereIn method verifies that a given column's value is contained within the given array: