Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent Pluck without losing the key

I have the following collection in Laravel:

 ["TheNumbers":[{"episodeID":16818,"episodeNumber":100,"created_at":null,"updated_at":null},{"episodeID":16818,"episodeNumber":210,"created_at":"2017-02-20 21:30:38","updated_at":"2017-02-20 21:30:38"}]

If I run the following code:

$TheEpisode->TheNumbers->pluck('episodeNumber');

I will get the following result:

[100,210]

I would like to keep the keys for each number, how can I achieve this?

EDIT: EXPECTED RESULT:

This is my expected result:

[{"episodeNumber":100},{"episodeNumber":210}]

PHILIS PETERS (improved)

TheEpisode->TheNumbers->reduce(function ($result, $episode) {
          $episodeData = (collect())->put('episodeNumber', $episode['episodeNumber']);
          $result[] = $episodeData;
          return $result;
        }));
like image 354
Coder Avatar asked Feb 20 '17 22:02

Coder


4 Answers

Pluck() can take two params. The second of which is what the value can be keyed by.

You should be able to do:

$TheEpisode->TheNumbers->pluck('episodeNumber', 'episodeID');

Hope this helps!

like image 148
Rwd Avatar answered Oct 20 '22 17:10

Rwd


Try something like this, it should work using map...

return $TheEpisode->TheNumbers->map(function ($episode) {
    return ['episodeNumber' => $episode['episodeNumber']];
});
like image 43
Mike Barwick Avatar answered Oct 20 '22 17:10

Mike Barwick


This can be simply achieved by passing a second argument to pluck. From the documentation:

You may also specify how you wish the resulting collection to be keyed:

$plucked = $collection->pluck('name', 'product_id');

$plucked->all();

// ['prod-100' => 'Desk', 'prod-200' => 'Chair']
like image 8
shxfee Avatar answered Oct 20 '22 17:10

shxfee


$collection->forget(['created_at', 'updated_at]);

This will simply left two first key-value pairs. Worth to keep in mind:

forget does not return a new modified collection; it modifies the collection it is called on.

Laravel docs

This should work properly:

$collection->only(['episodeID', 'episodeNumber']);
like image 4
wujt Avatar answered Oct 20 '22 17:10

wujt