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.
1$key = 'name'; 2// Still valid 3if ($this->collection->has($key) === false) { 4 $this->collection->put($key, ...); 5} 6 7return $this->collection->get($key); 8 9// Using the `getOrPut()` method with closure10return $this->collection->getOrPut($key, fn() => ...);11 12// Or pass a fixed value13return $this->collection->getOrPut($key, $value='teacoders');
Tip given by @Teacoders