mySun
mySun

Reputation: 1696

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 :-)

Upvotes: 2

Views: 2658

Answers (2)

Saravanan Sampathkumar
Saravanan Sampathkumar

Reputation: 3261

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

Upvotes: 3

Loren
Loren

Reputation: 12741

You'd need to use each to go through the outer array and min in the inner one to get the min price. You'd then have to search to find the index and go back and use that to get the name/price. At that rate, you're probably best off writing your own function that reads more nicely.

$collection->each(function ($item, $brand) {
    $minPrice = $item->min('price');
    $minIndex = $item->search(function ($item) use ($minPrice) { 
        return $item['price'] == $minPrice
    });
    echo $brand.' '.$item[$minIndex]['name']. ' '.$item[$minIndex]['price'];
});

You may have to collect on the inner items as I can't remember if collect automatically nests all the collections

Upvotes: 1

Related Questions