How do I use validateWithBag90
in Laravel 9? I tried a lot of combinations and I'm getting a bit frustrated.
$validator = Validator::make($request->all(), [
'old' => 'required',
'new' => 'required|string|confirmed',
]);
if ($validator->fails()) {
return redirect()->back()->with('error', $validator);
}
I'm getting this error.
Serialization of 'Closure' is not allowed
Any ideas?
CodePudding user response:
After determining whether the request validation failed, you may use the
withErrors
method to flash the error messages to the session. When using this method, the$errors
variable will automatically be shared with your views after redirection, allowing you to easily display them back to the user. ThewithErrors
method accepts a validator, aMessageBag
, or a PHParray
.
Instead of:
// ...
->with('error', $validator); ❌
// ...
Use this:
// ...
if ($validator->fails()) {
return redirect()
->back()
->withErrors($validator) ✅
->withInput();
}
// ...
Addendum
Displaying The Validation Errors
An
$errors
variable is shared with all of your application's views by theIlluminate\View\Middleware\ShareErrorsFromSession
middleware, which is provided by theweb
middleware group. When this middleware is applied an$errors
variable will always be available in your views, allowing you to conveniently assume the$errors
variable is always defined and can be safely used. The$errors
variable will be an instance ofIlluminate\Support\MessageBag
.
<!-- /resources/views/post/create.blade.php -->
<h1>Create Post</h1>
@if ($errors->any())
<div >
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<!-- Create Post Form -->