phparrayslaravel

Laravel collection how to remove a specific key from all items?


It sounded crazy simple to me at first but I can't find the solution!

Here is My collection :

Collection {#433
  #items: array:432 [
    0 => array:5 [
      "word_id" => 12218
      "name" => "ordered"
      "rank" => 12217
      "is_real" => 1
      "id" => 1
    ]
    1 => array:5 [
      "word_id" => 12097
      "name" => "one-dimensional"
      "rank" => 12096
      "is_real" => 1
      "id" => 2
    ]
    2 => array:5 [
      "word_id" => 19679
      "name" => "watery"
      "rank" => 19678
      "is_real" => 1
      "id" => 3
    ]
    .
    .
    .

But I want it to be like this :

Collection {#433 
  #items: array:432 [
    0 => array:5 [
      "name" => "ordered"
      "id" => 1
    ]
    1 => array:5 [
      "name" => "one-dimensional"
      "id" => 2
    ]
    2 => array:5 [
      "name" => "watery"
      "id" => 3
    ]
    .
    .
    .

How can it be done with laravel collection? Do I have to change my collection to array and do the manipulation myself? How?


Solution

  • $collection = $collection->map(function ($item) {
        return array_only($item, ['id', 'name']);
    });