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.

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 closure
10return $this->collection->getOrPut($key, fn() => ...);
11 
12// Or pass a fixed value
13return $this->collection->getOrPut($key, $value='teacoders');

Tip given by @Teacoders

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 22 courses (477 lessons, total 38 h 20 min)
  • 2 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord