1

In my application, there are two models:

  • person
  • subject

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
            ],
},

1 Answer 1

2

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;
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thought about looping through the collection, wondered if there's a more elegant solution
@YonatanNaxon you could use your own method instead of with() to load related data (or your own collection method), but this is a bad idea for many reasons. I wouldn't recommend you modify collection at all, but if you need to, using map() is the best solution here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.