The issue you're encountering is likely due to the fact that Laravel's validation errors are not being properly caught and handled in your JavaScript code. When validation fails, Laravel will return a 422 Unprocessable Entity status code along with the validation errors. However, your JavaScript code is not set up to properly handle this scenario.
Here's a step-by-step solution to address this:
-
Ensure Laravel is returning a 422 status code on validation failure:
Your Laravel controller method looks correct, but make sure that the validation rule is being applied correctly. If the
namefield is empty, Laravel should automatically return a 422 status code with the validation errors. -
Update your JavaScript code to handle the 422 status code properly:
You need to modify your JavaScript code to handle the 422 status code and parse the response JSON to get the validation errors.
Here is the updated JavaScript code:
seed_form.addEventListener('submit', function(e) {
e.preventDefault();
const headers = new Headers();
headers.append("X-CSRF-TOKEN", csrf_token[0]);
let form_data = new FormData(seed_form);
if (page == 'edit') form_data.append("_method", 'PUT');
submit_button.disabled = true;
spinner.classList.add('visible');
let route = (page == 'create') ? '/semi' : `/semi/${seed_id}`;
fetch(route, {
method: 'POST',
body: form_data,
headers: headers
}).then((response) => {
if (!response.ok) {
if (response.status === 422) {
return response.json().then((errorData) => {
throw { status: 422, errors: errorData };
});
} else {
throw new Error(`HTTP error, status = ${response.status}`);
}
}
return response.json();
}).then((data) => {
console.log('data', data);
// Handle success response
}).catch((error) => {
if (error.status === 422) {
console.log('Validation errors:', error.errors);
// Handle validation errors
} else {
console.error('Error:', error);
}
}).finally(() => {
submit_button.disabled = false;
spinner.classList.remove('visible');
});
});
Explanation:
-
Check for 422 status code:
- In the
.thenblock, ifresponse.okisfalseand the status is422, parse the response JSON to get the validation errors and throw an error object containing the status and errors.
- In the
-
Catch block:
- In the
.catchblock, check if the error status is422and log the validation errors. Otherwise, log the general error.
- In the
-
Finally block:
- Re-enable the submit button and hide the spinner regardless of the outcome.
This should ensure that your JavaScript code properly handles validation errors returned by Laravel and logs them to the console.