Reputation: 3731
I have Collection like this
[
{
"user_id":1,
"chat_id":1,
"chat_hidden":0,
"access_time":"2017-06-10 00:28:11",
"name":"Dr. Harley Raynor",
"image_url":null
},
{
"user_id":1,
"chat_id":2,
"chat_hidden":1,
"access_time":"2017-06-12 10:59:37",
"name":"Dr. Harley Raynor",
"image_url":null
}
]
if i want to take only user_id
from it, and format array like this
[
{
"user_id":1
},
{
"user_id":1
}
]
i write Collection()->pluck('user_id')
and everything works fine, but what if i need to take several items? Like user_id
and chat_id
? I tried ->pluck('user_id', 'chat_id')
, ->pluck(['user_id', 'chat_id'])
and ->only('user_id', 'chat_id')
nothing seems to work.
Upvotes: 2
Views: 154
Reputation: 3449
Just use map
;
$myCollection->map(function($item) {
return [
'user_id' => $item->user_id,
....
];
});
But if you are building an api, I strongly recommend you to use some sort of transformers such https://github.com/spatie/laravel-fractalto handle inclusion and exclusion in the future as the service mature.
Upvotes: 1