CollectionsTIP 07 / 08
Get an Existing Key or Insert a Value If It Doesn't Exist and Return the Value.
In Laravel 8.81 getOrPut method to Collections that simplifies the use-case where you want to either get an existing key or insert a value if it doesn't exist and return the value.
$key = 'name';
// The existing approach remains valid:
if ($this->collection->has($key) === false) {
$this->collection->put($key, ...);
}
return $this->collection->get($key);
// Use getOrPut() with a closure:
return $this->collection->getOrPut($key, fn() => ...);
// Alternatively, pass a fixed value:
return $this->collection->getOrPut($key, $value='teacoders');