To handle deferred props and lazy load relationships with InertiaJS, you can use a combination of eager loading and Inertia's lazy loading feature. This approach allows you to load only the necessary data initially and defer the loading of other data until it's needed, which can be particularly useful for optimizing performance when dealing with large datasets or complex relationships.
Here's a refined solution based on your example:
class ShowController extends Controller {
public function __invoke(TeamShowRequest $request, Team $team) {
// Eager load relationships that are always needed
$team->load(['results']);
return Inertia::render('Team/Show', [
'team' => $team,
// Use Inertia's lazy loading for relationships that can be deferred
'players' => Inertia::lazy(fn () => $team->players()->get()),
'coaches' => Inertia::lazy(fn () => Coach::where('team_id', $team->id)->get()),
]);
}
}
Explanation:
-
Eager Loading: Use
$team->load(['results']);to load relationships that are always required when the page is initially rendered. This ensures that the necessary data is available immediately. -
Lazy Loading with Inertia: Use
Inertia::lazy()for relationships that can be loaded on demand. This is useful for data that might not be needed immediately or for large datasets that could impact performance if loaded all at once. -
Polling and Partial Reloads: If you plan to use polling or partial reloads, you can trigger these lazy-loaded properties to refresh as needed. InertiaJS supports partial reloads, which can be used to update specific parts of the page without reloading the entire component.
This approach provides a balance between performance and functionality, allowing you to optimize data loading based on your application's specific needs.