Skip to content

Commit 53ebf77

Browse files
committed
Add lazy props feature
1 parent 0366204 commit 53ebf77

File tree

3 files changed

+32
-1
lines changed

3 files changed

+32
-1
lines changed

src/LazyProp.php

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
<?php
2+
3+
namespace Inertia;
4+
5+
use Illuminate\Support\Facades\App;
6+
7+
class LazyProp
8+
{
9+
protected $callback;
10+
11+
public function __construct(callable $callback)
12+
{
13+
$this->callback = $callback;
14+
}
15+
16+
public function __invoke()
17+
{
18+
return App::call($this->callback);
19+
}
20+
}

src/Response.php

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,9 +54,15 @@ public function toResponse($request)
5454

5555
$props = ($only && $request->header('X-Inertia-Partial-Component') === $this->component)
5656
? Arr::only($this->props, $only)
57-
: $this->props;
57+
: array_filter($this->props, function ($prop) {
58+
return ! ($prop instanceof LazyProp);
59+
});
5860

5961
array_walk_recursive($props, function (&$prop) use ($request) {
62+
if ($prop instanceof LazyProp) {
63+
$prop = App::call($prop);
64+
}
65+
6066
if ($prop instanceof Closure) {
6167
$prop = App::call($prop);
6268
}

src/ResponseFactory.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,11 @@ public function getVersion()
5454
return (string) $version;
5555
}
5656

57+
public function lazy(callable $callback)
58+
{
59+
return new LazyProp($callback);
60+
}
61+
5762
public function render($component, $props = [])
5863
{
5964
if ($props instanceof Arrayable) {

0 commit comments

Comments
 (0)