Skip to content

Instantly share code, notes, and snippets.

@Vigowebs
Created October 12, 2022 06:40
Show Gist options
  • Save Vigowebs/fddb5809272f25ff18d0b03e303fe112 to your computer and use it in GitHub Desktop.
Save Vigowebs/fddb5809272f25ff18d0b03e303fe112 to your computer and use it in GitHub Desktop.
getOrPut() can be used to fetch an item if it already exists, or insert it and fetch it if it doesn't. This can be really useful when building up a Collection with data from multiple sources and don't want duplicate items in our data.
// ❌
if (! $collection->has($key)) {
$collection->put($key, $this->builtItem($data));
}
return $collection->get($key);
// ✔️
return $collection->getOrPut($key, fn () => $this->buildItem($data));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment