I have a collection
$collection = collect([['title' => 'Lean Startup', 'category' => 'story', 'price' => 10], ['title' => 'The One Thing', 'category' => 'romance', 'price' => 15], ['title' => 'Laravel: Code Bright', 'category' => 'suspense', 'price' => 20], ['title' => 'The 4-Hour Work Week', 'category' => 'thrill', 'price' => 5]]);
I want to get 'title', 'category' column how can I get it?
Thats one way to do it
$collection = collect([['title' => 'Lean Startup', 'category' => 'story', 'price' => 10], ['title' => 'The One Thing', 'category' => 'romance', 'price' => 15], ['title' => 'Laravel: Code Bright', 'category' => 'suspense', 'price' => 20], ['title' => 'The 4-Hour Work Week', 'category' => 'thrill', 'price' => 5]]);
$collection2 = $collection->map(function ($item) {
return ['title' => $item['title'], 'category' => $item['category']];
});
@kboduch I know this way actually I do this way as I couldn't find any other solution. But laravel collection pluck method could have been a good choice to solve this problem. But for now it accepts only string.
$collection->only(['title', 'category']);
@milosdakic That was my first thought, but collection is made of arrays.
@milosdakic sorry this doesn't work for multidimensional array
$collection->collapse()->only(['title', 'category'])
Collapse the multidimensional array first then use only.
@milosdakic sorry that didn't work but thanks for your effort.
@arifmahmudrana If you don't mind returning a collection:
$collection2 = $collection->map(function ($item) { return collect($item)->only(['title', 'price']); });
//Or make it a macro:
use Illuminate\Support\Collection;
Collection::macro('transpose', function(...$keys) {
return $this->map(function ($item) use ($keys) { return (new self($item))->only($keys); });
});
Although I would agree with @kboduch and keep the solution as a map.
@arifmahmudrana Have you solved? If yes please close the issue.
@billmn I am looking for if there is any existing solution in laravel not yet found that.
@arifmahmudrana this question is better suited to be asked at: https://laracasts.com/discuss
Agree with @userabuser, this is not a Laravel issue. Please ask suggestions in the Forum.
Is this solved even?
$collection->map->only('foo', 'bar');
Most helpful comment
Thats one way to do it
https://laravel.com/docs/5.1/collections#method-map