moonwalker
moonwalker

Reputation: 1177

Laravel 5.6 get all rows as arrays of values using Eloquent ORM

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

Answers (3)

dikirill
dikirill

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

jarguez01
jarguez01

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

Mahdi Younesi
Mahdi Younesi

Reputation: 7489

Use pluck method to achieve that

$items = \App\Item::pluck('name', 'id');

Upvotes: 0

Related Questions