Issue with Vue and Laravel Form Validation failing to return 422 response

I've been working on validating form data using Laravel and Vue on the backend, but I'm facing an issue with receiving a 422 response.

Within my controller function:

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

    $location = $request->isMethod('put') ? 
    Locations::findOrFail($request->id) : new Locations;

    $location->id = $request->input('id');
    $location->name = $request->input('name');
    $location->address = $request->input('address');
    $location->city = $request->input('city');
    $location->state = $request->input('state');
    $location->zip = $request->input('zip');
    $location->phone = $request->input('phone');

    if($location->save())
    {
        return new LocationsResource($location);
    }

Below is the Vue method:

addLocation() {
if (this.edit === false) {
        // Add
        fetch('api/location', {
          method: 'post',
          body: JSON.stringify(this.location),
          headers: {
            'content-type': 'application/json'
          }
        })
          .then(res => res.json())
          .then(data => {
            this.clearForm();
            alert('Location Added');
            this.fetchArticles();
          });

      } else {
        // Update
        fetch('api/location', {
          method: 'put',
          body: JSON.stringify(this.location),
          headers: {
            'content-type': 'application/json'
          }
        })
          .then(res => res.json())
          .then(data => {
            this.clearForm();
            alert('Locations Updated');
            this.fetchArticles();
          })

      }
      }

The form section is as follows:

<form @submit.prevent="addLocation" class="mb-3">
  <div class="form-group">
    <input type="text" class="form-control" placeholder="Name" v-model="location.name">
    <input type="text" class="form-control" placeholder="City" v-model="location.city">
    <input type="text" class="form-control" placeholder="State" v-model="location.state">
  </div>

  <button type="submit" class="btn btn-light btn-block">Save</button>
</form>

Although I receive appropriate status codes back for CRUD operations in the Network->XHR tab within the inspector, I do not get a 422 HTTP status code when the form fails validation. When submitting the form with no data, it does not save but fails to send any status code, leaving the user without feedback. Appreciate any assistance on resolving this issue. Thank you!

Answer №1

After making some adjustments, I successfully included the "accept": "application/json" in the header of my addLocation method.

Answer №2

$this->validate($request, [
    'username' => 'required',
    'email' => 'required',
    'password' => 'required'
    ]);

This approach is quite unusual to me. I am not aware of the validate function being in the controller. Have you considered using this alternative method?

$request->validate([
    'username' => 'required',
    'email' => 'required',
    'password' => 'required'
    ]);

Answer №3

Here is the code that I have attempted:

 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']);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Learn how to prompt an event in Angular when the browser is closed instead of being refreshed

Is there a method to remove a token from local storage only when the browser is closed, rather than on refresh? I have attempted the approach below but it is also being removed on refresh. If possible, please suggest a more effective solution as my previ ...

Convert HEX to RGB color format

Is it possible to utilize jQuery to call a function that converts a HEX value to RGB and then insert the HTML? Here is the JavaScript code: function convertHexToRGB( color ) { var r, g, b; if ( color.charAt(0) == '#' ) { color = ...

Here is a new version: "AJAX button enables updating a single row in SQLite database through PHP."

My webpage features a table that shows values entered by a user, along with two buttons for removal and completion. The table is part of a layout with three tabs named Tab1, Tab2, and Tab3. Each tab contains its own table displaying information related to ...

Loading images in advance using JavaScript

I have been searching through multiple forums and cannot seem to figure out the issue. The problem I am encountering is related to a website where there are three images with a hover effect. When the page first loads, there is a delay in loading the backgr ...

What causes a Unity3D app [exported to an Xcode project] to experience issues due to the presence of "unsealed contents in the bundle root" in ip_unity_plugin.bundle?

As a Swift developer, I am working on submitting an app created by my Unity3D developer colleague to the App Store. Within the Xcode project for this app, there is a file located here: Frameworks/Plugins/x86_64/ip_unity_plugin.bundle This file seems to b ...

After the jquery.show function is executed, an unexpected WebDriverException occurred, indicating an unknown error that prevents focusing

Here is my line of JavaScript code: $('#name').show(); And this is my webdriver code line: wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("name"))).sendKeys("Some Name"); When running the test, I encountered an exception: Web ...

Tips on how to personalize single-click to double-click functionality in JavaScript

Is there a way to change the single click event to a double click? It needs to register as a double click if the second click occurs within 300 milliseconds. ...

Is there a way to bring in an NPM module without utilizing the keywords 'require' or 'import'?

After spending hours searching for a solution, I am still struggling with importing third-party libraries into my project that does not support 'import' or 'require'. It's frustrating to hit a roadblock like this, especially when w ...

Dealing with adding up optional values from v-model in Vue.js can be a challenging task

Within this function, I need to display the remaining amount. remainingAmount: function() { return parseFloat(this.sumAmount) - (parseFloat(this.cash) + parseFloat(this.kNet) + parseFloat(this.kNetOnline)); } The three parameters cash ...

position the tooltip within the ample available space of a container in an angular environment

In my editor, users can create a banner and freely drag elements within it. Each element has a tooltip that should appear on hover, positioned on the side of the element with the most space (top, left, bottom, right). The tooltip should never extend outsid ...

What is preventing ColladaLoader.js in Three.js from loading my file?

Recently, I decided to experiment with three.js and wanted to load a .dae file called Raptor.dae that I obtained from Ark Survival Evolved. Despite having some web development knowledge, I encountered an issue when trying to display this particular file in ...

Tips for utilizing the async.js library in combination with the await keyword?

Currently, I am working on integrating the async library to continuously poll an API for a transaction until it is successful. router.get('/', async function (req, res) { let apiMethod = await service.getTransactionResult(txHash).execute(); ...

What is the best way to Retrieve Data and Manage State using Hooks?

I have a variable called resourcesData which contains 5 empty arrays and 3 arrays with objects of data. I am unsure of how to pass these 3 arrays with objects of data into useState and manage them. const resourcesData = data; https://i.sstatic.net/fuXhi.p ...

Attempting to generate a dynamic animation of a bouncing sphere confined within a boundary using components, but encountering

I'm new to JavaScript and currently working on a project involving a bouncing ball inside a canvas. I was able to achieve this before, but now I'm attempting to recreate it using objects. However, despite not encountering any errors, the animatio ...

Tips for populating an input field with data from a database using the .append method

I have a button that generates a new input field along with a default field <div class="container1"> <button class="add_form_field">Add Title</button> <div class="form-group label-floating"> <input type="text" id="ti ...

Challenges with Expanse in Object-Oriented JavaScript

I'm currently working on incorporating objects from a JSON file into an array within my JavaScript object using the $.getJSON() function in jQuery. However, I've encountered scope challenges where the array elements appear to be defined inside th ...

What could possibly be causing a syntax error in my JavaScript code?

<script type="text/javascript> $(document).ready(function(){ $("a.grouped_elements").fancybox( 'transitionIn' : 'elastic', 'transitionOut' : 'elastic', 'speedIn' : 600, ...

Creating a React Native project without the use of TypeScript

Recently I dived into the world of React Native and decided to start a project using React Native CLI. However, I was surprised to find out that it uses TypeScript by default. Is there a way for me to create a project using React Native CLI without TypeS ...

Amcharts does not display the percentage value

I've been working on creating a bar graph using amcharts and I'm trying to show the percentage on top of each bar. Here is the code snippet I have so far: $.ajax({ url: "https://daturl", contentType: "application/json; charset=utf-8", ...

Exploring Three.js: How to Integrate and Utilize 3D Models

Hey there! I've been doing a lot of research online, but I can't seem to find a solution that works for me. My question is: How can I integrate 3D models like collada, stl, obj, and then manipulate them using commands like model.position.rotation ...