Search code examples
laravellaravel-5.3collect

How to use collect in Laravel 5.3?


I need use collect in Laravel 5.3 but I need help.

For Example:

$collection = collect([
  'Apple' => [
      ['name' => 'iPhone 6S', 'price' => '200'],
      ['name' => 'iPhone 7S', 'price' => '250'],
  ],
  'Samsung' => [
      ['name' => 'Galaxy S7', 'price' => '300']
      ['name' => 'Galaxy note', 'price' => '150']
  ],
]);
  1. How to get Apple or Samsung name with collect? I need get brand name.
  2. How to get (name and price) the cheapest price of each brand.

Thank you :-)


Solution

  • You could achieve that through mapWithKeys

    /* First get the minimum price */
    
    $min = $collection->flatten(1)->pluck('price')->min();
    
    /* Then perform the filteration */
    
    $final = $collection->mapWithKeys(function($value, $key) use ($min) {
        $result = collect($value)->filter(function($inner) use ($min){
            return $inner['price'] === $min;
        })->keys()->first();
    
        return $result ? [$key => $value[$result]]: [];
    });
    

    When you run the above code, you will get

    Illuminate\Support\Collection Object
    (
        [items:protected] => Array
            (
                [Samsung] => Array
                    (
                        [name] => Galaxy note
                        [price] => 150
                    )
    
            )
    
    )
    

    Now to get brand name simply do

    $final->keys()->first() // Samsung
    

    To get model name

    $final->pluck('name')->first() // Galaxy note