getOrPut feature was introduced in Laravel 8.81 and it’s a pretty amazing oneliner.
getOrPut helps you to get an existing key or put the value if it doesn’t exist and return the value on a collection.
As of now you want to have three lines of code to achieve this, but getOrPut changes everything.
if ($this->collection->has($key) === false) { $this->collection->put($key, $this->create($data)); }
You can have it like this, and if it’s found it returns the value or it creates a new one.
return $this->collection->getOrPut($key, $value); /for a fixed value
Or you can use the getOrPut method with a closure.
return $this->collection->getOrPut($key, fn () => $this->create($data));
Did this post help you?
Tutsplanet brings in-depth and easy tutorials to understand even for beginners. This takes a considerable amount of work. If this post helps you, please consider supporting us as a token of appreciation:
- Just want to thank us? Buy us a Coffee
- May be another day? Shop on Amazon using our links.
Your prices won't change but we get a small commission.
Leave a Reply