Skip to content

Commit f802df2

Browse files
authored
Merge pull request #198 from inertiajs/add-error-bag-support
Add error bag support
2 parents 6d42769 + db7e331 commit f802df2

File tree

2 files changed

+26
-2
lines changed

2 files changed

+26
-2
lines changed

src/Middleware.php

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -147,8 +147,14 @@ public function resolveValidationErrors(Request $request)
147147
return (object) collect($bag->messages())->map(function ($errors) {
148148
return $errors[0];
149149
})->toArray();
150-
})->pipe(function ($bags) {
151-
return $bags->has('default') ? $bags->get('default') : $bags->toArray();
150+
})->pipe(function ($bags) use ($request) {
151+
if ($bags->has('default') && $request->header('x-inertia-error-bag')) {
152+
return [$request->header('x-inertia-error-bag') => $bags->get('default')];
153+
} elseif ($bags->has('default')) {
154+
return $bags->get('default');
155+
} else {
156+
return $bags->toArray();
157+
}
152158
});
153159
}
154160
}

tests/MiddlewareTest.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,24 @@ public function test_default_validation_errors_can_be_overwritten()
140140
]);
141141
}
142142

143+
public function test_validation_errors_are_scoped_to_error_bag_header()
144+
{
145+
Session::put('errors', (new ViewErrorBag())->put('default', new MessageBag([
146+
'name' => 'The name field is required.',
147+
'email' => 'Not a valid email address.',
148+
])));
149+
150+
Route::middleware([StartSession::class, ExampleMiddleware::class])->get('/', function () {
151+
$errors = Inertia::getShared('errors')();
152+
153+
$this->assertIsObject($errors);
154+
$this->assertSame('The name field is required.', $errors->example->name);
155+
$this->assertSame('Not a valid email address.', $errors->example->email);
156+
});
157+
158+
$this->withoutExceptionHandling()->get('/', ['X-Inertia-Error-Bag' => 'example']);
159+
}
160+
143161
public function test_middleware_can_change_the_root_view_via_a_property()
144162
{
145163
$this->prepareMockEndpoint(null, [], new class extends Middleware {

0 commit comments

Comments
 (0)