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
withErrorsmethod to flash the error messages to the session. When using this method, the$errorsvariable will automatically be shared with your views after redirection, allowing you to easily display them back to the user. ThewithErrorsmethod 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
$errorsvariable is shared with all of your application's views by theIlluminate\View\Middleware\ShareErrorsFromSessionmiddleware, which is provided by thewebmiddleware group. When this middleware is applied an$errorsvariable will always be available in your views, allowing you to conveniently assume the$errorsvariable is always defined and can be safely used. The$errorsvariable 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 -->
