Petro Gromovo
Petro Gromovo

Reputation: 2243

With mapping in laravel 7 app collect data

In laravel 7 app I use mapping when I need to collect columns in array

        $retArray['categoryLabels'] = Category
            ::get()
            ->map(function ($item) {
                return ['code' => $item->id, 'label' => $item->title];
            })
            ->all();

I wonder if there is some method(like pluck) for this purpose ?

Thanks!

Upvotes: 0

Views: 146

Answers (1)

Donkarnash
Donkarnash

Reputation: 12845

Say the categories are like

code: web label: Web Development

code: php label: PHP Programming

code: javascript label: Javascript Frameworks

Use mapWithKeys

$retArray['categoryLabels'] = Category::get()
    ->mapWithKeys(function ($item) {
        return ['code' => $item->id, 'label' => $item->title];
    })
    ->all();

mapWithKeys will give output as

//Value of $retArray['categoryLabels']
//similar to using pluck()

[
    'web' => 'Web Development',
    'php' => 'PHP Programming',
    'javascript' => 'Javascript Frameworks'
}

Another way

$retArray['categoryLabels'] = Category::select('code', 'label')
    ->get()
    ->toArray();

will give output as

//Value of $retArray['categoryLabels']

[
    ['code' => 'web', 'label' => 'Web Development'],
    ['code' => 'php', 'label' => 'PHP Programming'],
    ['code' => 'javascript', 'label' => 'Javascript Frameworks']
]

Upvotes: 1

Related Questions