What is getOrPut in Laravel?

What is getOrPut in Laravel? | ninjasquad

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));

Editorial Staff

Editorial Staff at Tutsplanet is a dedicated team to write various tutorials about subjects like Programming, Technology and Operating Systems.

Source: Internet

Leave a Comment

We are offering free coding tuts