Skip to content

Instantly share code, notes, and snippets.

@KABBOUCHI
Last active October 5, 2020 20:02
Show Gist options
  • Save KABBOUCHI/bd83b1f5f689d38c3e007ecae3ecfc08 to your computer and use it in GitHub Desktop.
Save KABBOUCHI/bd83b1f5f689d38c3e007ecae3ecfc08 to your computer and use it in GitHub Desktop.
Inertia - Evaluate lazy props only if requested
<?php
namespace App\Providers;
use App\Inertia\ResponseFactory;
use Illuminate\Support\ServiceProvider;
use Inertia\ResponseFactory as InertiaResponseFactory;
class AppServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->singleton(InertiaResponseFactory::class, ResponseFactory::class);
}
}
<!-- Example -->
<template>
<div>
<div v-if="users">
....
</div>
<div v-else>
loading...
</div>
</div>
</template>
<script>
export default {
props: ['users'],
created() {
this.$inertia.reload({
only: ['users']
})
}
}
</script>
<?php
namespace App\Inertia;
use Inertia\Response as InertiaResponse;
use Closure;
use Illuminate\Support\Arr;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\App;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Contracts\Support\Responsable;
use Illuminate\Support\Facades\Response as ResponseFactory;
class Response extends InertiaResponse
{
public function toResponse($request)
{
$only = array_filter(explode(',', $request->header('X-Inertia-Partial-Data')));
$props = ($only && $request->header('X-Inertia-Partial-Component') === $this->component)
? Arr::only($this->props, $only)
: $this->props;
array_walk_recursive($props, function (&$prop, $propName) use ($request, $only) {
if ($prop instanceof Closure) {
if ($request->header('X-Inertia') && in_array($propName, $only))
$prop = App::call($prop);
else
$prop = null;
}
if ($prop instanceof Responsable) {
$prop = $prop->toResponse($request)->getData();
}
if ($prop instanceof Arrayable) {
$prop = $prop->toArray();
}
});
$page = [
'component' => $this->component,
'props' => $props,
'url' => $request->getRequestUri(),
'version' => $this->version,
];
if ($request->header('X-Inertia')) {
return new JsonResponse($page, 200, [
'Vary' => 'Accept',
'X-Inertia' => 'true',
]);
}
return ResponseFactory::view($this->rootView, $this->viewData + ['page' => $page]);
}
}
<?php
namespace App\Inertia;
use Illuminate\Contracts\Support\Arrayable;
use Inertia\ResponseFactory as InertiaResponseFactory;
class ResponseFactory extends InertiaResponseFactory
{
public function render($component, $props = [])
{
if ($props instanceof Arrayable) {
$props = $props->toArray();
}
return new Response(
$component,
array_merge($this->sharedProps, $props),
$this->rootView,
$this->getVersion()
);
}
}
<?php
//Example
Route::get('/', function () {
return inertia('Index', [
"users" => function () {
sleep(3);
return \App\Models\User::all();
}
]);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment