Laravel
Deep Dive into get() method in Laravel Collection
If you use Laravel, I am sure that you already used get()
method from the collection. Today, I will try to deep dive into get() method in Laravel collection.
#Table of Contents
#Uses
$data = [
"foo_key" => "foo value",
"bar_key" => "bar value",
"baz_key" => "baz value",
];
$getFoo = collect($data)->get("foo_key");
dd($getFoo);
// foo value
#How get() method works?
Illuminate\Support\Collection
/**
* Get an item from the collection by key.
*
* @param mixed $key
* @param mixed $default
* @return mixed
*/
public function get($key, $default = null)
{
if (array_key_exists($key, $this->items)) {
return $this->items[$key];
}
return value($default);
}
#Investigate:
- It requires a
$key
. - It checks the
$key
in the given array date incollect()
method. - If
$key
found in the array, then it returns the value
:question: What if the given $key
doesn't have any associated value? What should it returns?
Then it will return the default value that is null
.
public function get($key, $default = null)
.
.
You can also change the default value. For example-
$data = [];
$getFoo = collect($data)->get("foo", 'Nothing found');
dd($getFoo); // Nothing found
If given $key
doesn't match in the array, then it called another global functions named value()
/**
* Return the default value of the given value.
*
* @param mixed $value
* @return mixed
*/
function value($value, ...$args)
{
return $value instanceof Closure ? $value(...$args) : $value;
}
#Investigate:
It check if no Closure
pass, then just return the given value.
#Can we send the closure also?
Yes, you can do that also. You can manipulate the entire response.
For example-
$data = [];
$getFoo = collect($data)->get("foo", function () {
return "Response from closure";
});
dd($getFoo); //Response from closure