6

Is there any method to remove properties from multidimensional collections?

e.g I have

public function getPossibleAnswersAttribute()
{
    return collect([
        [
            'option' => 'A',
            'answer' => $this->answer_1,
            'points' => $this->answer_1_value
        ],
        [
            'option' => 'B',
            'answer' => $this->answer_2,
            'points' => $this->answer_2_value
        ],
        [
            'option' => 'C',
            'answer' => $this->answer_3,
            'points' => $this->answer_3_value
        ],
        [
            'option' => 'D',
            'answer' => $this->answer_4,
            'points' => $this->answer_4_value
        ]
    ]);
}

public function getPossibleAnswersWithoutPointsAttribute()
{
    $answers = $this->getPossibleAnswersAttribute()
    ->except(['0.points']);
    return $answers;
}

I'm trying to get the same collection but without the points key/property.

I know I could do it something like

->map(function ($item) {
    unset($item['points']);
    return $item;
});

However I'm hoping there is a more fluent way of doing this, as I've found I can do ->except(['0.points']); which removes it from the first, I was thinking is there like a magic keyword which counts as a key? similarly to ->except(['#.points']); so it does it for each?

owenmelbz
  • 6,180
  • 16
  • 63
  • 113

1 Answers1

0

For now (Laravel 5.3) there is really nothing simpler than this map (or transform) method. For sure nothing that's as easy to understand when you come back to the code later.

You could extend Collection though, and implement wildcards in except similarly to how for example pluck does it, but for me that's an overkill.

Paul
  • 3,186
  • 1
  • 19
  • 22