Get the solution ↓↓↓
I have a Laravel collection like this (approximating using array syntax; the actual data is aCollection ofobjects obtained from an API response, not a local DB):
$rows = [
[
'id': 1,
'name': 'Sue',
'age': 23,
],
[
'id': 2,
'name': 'Joe',
'age': 25,
],
]
I want to extract a subset of the fields:
$subset = [];
foreach ($rows as $row) {
$subset[] = ['name' => $row['name'], 'age' => $row['age']];
}
So that I end up with:
$subset = [
[
'name': 'Sue',
'age': 23,
],
[
'name': 'Joe',
'age': 25,
],
]
What should I use to achieve that instead of thefor loop?
I found this suggestion, using a higher-order message, which made some kind of sense:
$subset = $rows->map->only(['name', 'age']);
but that just gives me aCollection ofnull values. Expanding it into a conventionalmap call produced the same effect. I feel like I want some kind ofmultipluck, but I'm not sure what that corresponds to!
It turns out that I was doing this correctly with the higher-ordermap->only approach. However, while the items in my collection were a kind ofModel, they were not a subclass or compatible implementation of the LaravelModel class, and lacked an implementation of theonly method. The author added the method, and now it works as expected.
You were close, but you don't chainmap andonly, andonly doesn't seem to work on a Collection of nestedarrays/objects.
So, for your case, usemap() with a Callback:
$rows = collect([
(object)[
'id' => 1,
'name' => 'Sue',
'age' => 23,
],
(object)[
'id' => 2,
'name' => 'Joe',
'age' => 25,
]
]);
$mapped = $rows->map(function ($row) {
return ['age' => $row->age, 'name' => $row->name];
});
dd($mapped->toArray());
Output of that would be:
array:2 [?�?
0 => array:2 [?�?
"age" => 23
"name" => "Sue"
]
1 => array:2 [?�?
"age" => 25
"name" => "Joe"
]
]
Note: If these arearrays and notobjects, then you'd do$row['age'] and$row['name'] instead of$row->age and$row->name. In Laravel, Models are both, and allow either syntax.
References:
https://laravel.com/docs/9.x/collections#method-map
https://laravel.com/docs/9.x/collections#method-only
Edit:
Some alternatives. If you have aCollection ofModels, then you can natively do:
$mapped = $rows->map(function ($model) {
return $model->only(['age', 'name']);
});
If you have aCollection ofCollections, then you can do:
$mapped = $rows->map(function ($collection) {
return $collection->only(['age', 'name']);
});
And lastly, if youarrays orobjects, you cancollect() and call->only():
$mapped = $rows->map(function ($row) {
return collect($row)->only(['age', 'name']);
});
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Find the answer in similar questions on our website.
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.
PHP (from the English Hypertext Preprocessor - hypertext preprocessor) is a scripting programming language for developing web applications. Supported by most hosting providers, it is one of the most popular tools for creating dynamic websites.
The PHP scripting language has gained wide popularity due to its processing speed, simplicity, cross-platform, functionality and distribution of source codes under its own license.
https://www.php.net/
Laravel is a free open source PHP framework that came out in 2011. Since then, it has been able to become the framework of choice for web developers. One of the main reasons for this is that Laravel makes it easier, faster, and safer to develop complex web applications than any other framework.
https://laravel.com/
Welcome to the Q&A site for web developers. Here you can ask a question about the problem you are facing and get answers from other experts. We have created a user-friendly interface so that you can quickly and free of charge ask a question about a web programming problem. We also invite other experts to join our community and help other members who ask questions. In addition, you can use our search for questions with a solution.
Ask about the real problem you are facing. Describe in detail what you are doing and what you want to achieve.
Our goal is to create a strong community in which everyone will support each other. If you find a question and know the answer to it, help others with your knowledge.