[Vuejs]-Vue and Laravel Form Validation not returning 422 response

3👍

I had to add “accept”: “application/json” to the header of the addLocation method.

1👍

$this->validate($request, [
    'name' => 'required',
    'city' => 'required',
    'state' => 'required'
    ]);

I’ve never seen such usage. I don’t think controller have the validate function. Try this:

$request->validate([
    'name' => 'required',
    'city' => 'required',
    'state' => 'required'
    ]);
👤mutas

0👍

The following code what i have tried

 const form_data = new FormData(document.querySelector('#form_data'));
 fetch("{{route('url')}}", {
       'method': 'post',
       body: form_data,
 }).then(async response => {
      if (response.ok) {
         window.location.reload();
      }
      const errors = await response.json();
      var html = '<ul>';
      for (let [key, error] of Object.entries(errors)) {
          for (e in error) {
              html += `<li>${error[e]}</li>`;
          }
      }
      html += '</ul>';
      //append html to some div

      throw new Error("error");
  })
  .catch((error) => {
     console.log(error)
  });

Controller

use Illuminate\Support\Facades\Validator;//Use at top of the page
$rules = [
    'file' => 'image|mimes:jpeg,png,jpg|max:1024',
    'field1' => 'required',
    'field2' => 'required'
   ];
$validator = Validator::make($request->post(), $rules);
if ($validator->fails()) {
   return response()->json($validator->errors(), 400);
}
session()->flash('flahs', ['status' => 'status', 'message' => 'message']);

Leave a comment