Home > Mobile >  How do you send validation errors to a blade view using the Validator facade? Error: Serialization o
How do you send validation errors to a blade view using the Validator facade? Error: Serialization o

Time:03-21

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:

Manually Creating Validators

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. The withErrors method accepts a validator, a MessageBag, or a PHP array.

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 the Illuminate\View\Middleware\ShareErrorsFromSession middleware, which is provided by the web 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 of Illuminate\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 -->
  • Related