Certainly! This is a common issue when using Inertia's lazy loading (Inertia::lazy or Inertia::optional) in combination with server-side validation errors. Here’s what’s happening and how you can fix it:
Problem Explanation
When you use Inertia::lazy or Inertia::optional to defer loading of certain props, those props are only loaded when explicitly requested (e.g., via a client-side visit with preserveState). However, when you submit a form and validation fails, Laravel typically redirects back with errors, but does not re-trigger the lazy-loaded data unless you explicitly request it again.
As a result, after a failed validation, your lazy-loaded data is missing, causing your component (inside <WhenVisible>) to go blank.
Solution
You need to ensure that the lazy-loaded data is always included when returning validation errors.
Option 1: Eagerly Load Data on Validation Failure
Instead of returning the lazy prop, return the actual data if validation fails.
Example Controller:
use Inertia\Inertia;
public function store(Request $request)
{
$validated = $request->validate([
'name' => 'required',
// other rules...
]);
// ...store logic...
return redirect()->route('your.route');
}
public function create()
{
return Inertia::render('YourComponent', [
'lazyData' => Inertia::lazy(fn () => $this->getLazyData()),
]);
}
// In your store method, on validation failure, return the data eagerly:
public function store(Request $request)
{
try {
$validated = $request->validate([
'name' => 'required',
// other rules...
]);
// ...store logic...
return redirect()->route('your.route');
} catch (\Illuminate\Validation\ValidationException $e) {
return Inertia::render('YourComponent', [
'lazyData' => $this->getLazyData(), // Eager load here!
'errors' => $e->errors(),
])->withErrors($e->errors());
}
}
Option 2: Always Load Data If Validation Fails
A more DRY approach is to check if there are errors and load the data accordingly:
public function create()
{
$lazyData = request()->old() || session('errors')
? $this->getLazyData()
: Inertia::lazy(fn () => $this->getLazyData());
return Inertia::render('YourComponent', [
'lazyData' => $lazyData,
]);
}
Summary
- Lazy props are not included on validation error redirects.
- On validation failure, return the actual data instead of a lazy prop.
- This ensures your component always has the data it needs, even after a failed form submission.
References:
Let me know if you need a more specific code example tailored to your setup!