phplaraveleloquentcollections

How can I delete a column in a multi-dimensional Laravel collection?


I just want to delete a column from a multi-dimensional collection.

$z = collect(
    ["x"=>"a", "y"=>"b", "z"=>"c"],
    ["x"=>"c", "y"=>"d", "z"=>"e"]
);

$z->deleteColumn("x");

$z should now have the data set:

[
   ["y"=>"b", "z"=> "c"]
   ["y"=>"d", "z"=> "e"]
]

I can use a map function with except but is there an easy one liner I'm missing? This seems pretty common.


Solution

  • Use the transform() method:

    $collection->transform(function($i) {
        unset($i->x);
        return $i;
    });