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!