Yonatan Naxon
Yonatan Naxon

Reputation: 639

Laravel QueryBuilder return array of values

In my application, there are two models:

there's a many-to-many relationship between those two.

In order to fetch all people (person) with their respective subjects, I do;

   $people = Person::with(['subjects' => function($query) {
     $query->select('id');
   }]);

Results in:

{
            ...

            "subjects": [
                {
                    "id": 16
                },
                {
                    "id": 21
                },
                {
                    "id": 32
                }
            ],
},

I am wondering is there an elegant way to get an array of subject ids instead:

{
            ...

            "subjects": [
                10,
                14,
                21,
                38
            ],
},

Upvotes: 1

Views: 730

Answers (1)

Alexey Mezenin
Alexey Mezenin

Reputation: 163748

You can use map() collection method. I've just tested this solution with many-to-many relationship and it works fine:

$collection->map(function ($i) {
    $i->subjectArray = $i->subjects->pluck('id')->toArray();
    unset($i->subjects);
    return $i;
});

Upvotes: 2

Related Questions