Reputation: 1177
I have an eloquent query that returns a collection:
$items = Item::get(['id', 'name']);
When I convert to JSON I get this:
[
{id: 1, name: "some name"},
{id: 2, name: "some other name"}
]
I want a result like this instead:
[
[1, "some name"],
[2, "some other name"]
]
How can I achieve this with Laravel 5.6 and eloquent ORM?
Upvotes: 4
Views: 8799
Reputation: 1903
I was getting error about inner toArray()
, so this worked for me:
$items = Item::get(['id', 'name'])->map(function($item) {
return array_values((array)$item);
})->toArray();
Upvotes: 2
Reputation: 194
You can use the toArray method
$items = Item::get(['id', 'name'])->map(function($item) {
return array_values($item->toArray());
});
Your $item variable will have something like this :
Illuminate\Support\Collection {
all: [
[
1,
"Peter",
],
[
2,
"Juan",
],
];
And the json representation :
[[1, "Peter"], [2, "Juan"]]
Upvotes: 5
Reputation: 7489
Use pluck method to achieve that
$items = \App\Item::pluck('name', 'id');
Upvotes: 0