value()
value() returns a value, or the result of calling it if it is a closure.
Syntax
value($maybeClosure);The value() helper returns whatever you give it — unless it is a closure, in which case it calls the closure and returns the result. This is useful for "default that might be lazy" patterns.
Any extra arguments are passed to the closure.
Example
Loading editor…
Press Run to execute the code.
When to use it
- A configuration builder passes either a static default value or a closure that computes the default lazily to value(), keeping the call site uniform.
- A factory method uses value() to resolve a setting that might be a plain string or a callable that queries the database only when needed.
- A helper function accepts a mixed argument and wraps it with value() so callers can pass either a literal or a deferred computation.
More examples
value() resolves closures and scalars
value() unwraps a closure by calling it, or returns any other value unchanged — making it ideal for lazy-default patterns.
$a = value('hello'); // => 'hello'
$b = value(42); // => 42
$c = value(fn() => 1 + 1); // => 2 (closure is called)
$d = value(null); // => nullLazy default with value()
Wrapping the default in a closure and resolving with value() defers the config() lookup until it is actually needed.
function setting(string $key, mixed $default = null): mixed
{
$stored = Setting::find($key)?->value;
// Only call the closure if $stored is null
return $stored ?? value($default);
}
$tz = setting('timezone', fn() => config('app.timezone'));
// The config() call happens only when no stored setting existsUse with() for fluent pipelines
with() is the companion to value(): it passes an object into a closure and returns whatever the closure returns, useful for inline scoping.
$result = with(new QueryBuilder(), function ($builder) {
return $builder
->select('id', 'name')
->from('users')
->where('active', 1)
->build();
});
// with() passes the value to the callback and returns the result
Discussion