Laravel Eloquent Pluck without losing the key
15,262
Solution 1
Try something like this, it should work using map
...
return $TheEpisode->TheNumbers->map(function ($episode) {
return ['episodeNumber' => $episode['episodeNumber']];
});
Solution 2
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!
Solution 3
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']
Solution 4
$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.
This should work properly:
$collection->only(['episodeID', 'episodeNumber']);
Related videos on Youtube
Comments
-
rossanmol over 1 year
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; }));
-
rossanmol about 7 yearsNope, this cannot happen because you are repeating episodeName for 2 times. What I want is like original idea but only episodeName field.
-
rossanmol about 7 yearsMethod does not exist
-
luke glenn jordan about 7 yearsare you sure you put "lists" not "list" ?
-
rossanmol about 7 yearsTried both. (I think in 5.4 lists method does not exist)
-
rossanmol about 7 yearsThis will work however this is not futureproof (If I will add more columns to my database later, they will be exposed)
-
rossanmol about 7 yearsit worked! However, I have multiple episodeNumber, only 1 is being shown.
-
rossanmol about 7 yearsThis is the output I am getting from your code: {"episodeNumber":210}
-
luke glenn jordan about 7 yearsOw i see, been using it in 5.2 maybe it is not available in 5.4
-
wujt about 7 yearsTry this: $collection->only(['episodeID', 'episodeNumber']);