lundi 12 novembre 2018

Laravel 5.7 - forget() or except() a specific item from collection where key could change at some point, so not to be trusted

I'm creating a collection from namespace classes that looks like this:

Collection {#458
  #items: array:3 [
    0 => array:2 [
      "name" => "Bug"
      "class" => "App\Models\BugTypes\Bug"
    ]
    1 => array:2 [
      "name" => "PreBug"
      "class" => "App\Models\BugTypes\PreBug"
    ]
    2 => array:2 [
      "name" => "Request"
      "class" => "App\Models\BugTypes\Request"
    ]
  ]
}

and want to forget() or return with except() the PreBug. Both collection methods expect a key, but as I am creating this and types in this namespace could be added at some point, the key could easily change. My method to create the collection looks like this:

$data = collect($names)->zip($classes)->transform(function ($values) {
        return [
            'name' => $values[0],
            'class' => $values[1]
        ];
    });

If I add ->except(1); or forget(1) right now, it would work until a new namespace was added that preceded P in the alphabet. So I either need to create a new key (probably the name) or find another way to return the result minus the PreBug type, no matter it's key. Thanks!



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire