Home > OS >  Laravel 8 - Pass validation errors back to frontend
Laravel 8 - Pass validation errors back to frontend

Time:10-16

I am using Laravel Framework 8.62.0.

I am validating a form the following way:

            $validator = Validator::make($request->all(), [
                'title_field' => 'required|min:3|max:100',
                'comment_textarea' => 'max:800',
                'front_image' => 'required|mimes:jpg,jpeg,png,bmp,tif',
                'back_image' => 'required|mimes:jpg,jpeg,png,bmp,tif',
                'price' => "required|numeric|gt:0",
                'sticker_numb' => "required|numeric|gt:0",
                'terms-checkbox' => "accepted",
            ]);

            if ($validator->fails()) {
                // Ooops.. something went wrong
                return Redirect::back()->withInput();//->withErrors($this->messageBag);
            }

I want to display errors in the frontend the following way:

@if ($errors->any())
<div class="alert alert-danger alert-dismissable margin5">
  <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
  <strong>Errors:</strong> Please check below for errors
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
</div>
@endif

However, my $error variable is emtpy, when validation errors exist, so the validation errors do not get shown in my frontend.

Any suggestions what I am doing wrong?

I appreciate your replies!

CodePudding user response:

You should pass the $validator to withErrors like:

if ($validator->fails()) {
    // Ooops.. something went wrong
    return Redirect::back()->withErrors($validator)->withInput();
}

CodePudding user response:

That's because your not passing errors.

Try this:

if ($validator->fails()) {
        return redirect()->back()->withErrors($validator)->withInput();
    }

CodePudding user response:

As the previous speakers said, you must of course return the errors. but you can also use the Request Validate Helper. it does this automatically.

$request->validate([...])

As soon as an error occurs, it returns a response with the errors.

https://laravel.com/docs/8.x/validation#quick-writing-the-validation-logic

  • Related