To handle validation errors from a Laravel backend in a Nuxt 3 frontend, you need to properly catch and process the error responses. Laravel typically sends validation errors with a 422 status code and a JSON response containing the validation messages.
Here's a step-by-step solution:
-
Make the API Request: Use Nuxt's
useFetchoruseAsyncDatato make the API request to your Laravel backend. -
Catch the Validation Error: Handle the error response and extract the validation messages.
-
Display the Validation Errors: Show the validation errors to the user in your Nuxt component.
Here's an example using useFetch:
<template>
<div>
<form @submit.prevent="submitForm">
<div>
<label for="name">Name:</label>
<input type="text" v-model="form.name" id="name" />
<span v-if="errors.name">{{ errors.name[0] }}</span>
</div>
<div>
<label for="email">Email:</label>
<input type="email" v-model="form.email" id="email" />
<span v-if="errors.email">{{ errors.email[0] }}</span>
</div>
<button type="submit">Submit</button>
</form>
</div>
</template>
<script setup>
import { ref } from 'vue'
import { useFetch } from '#app'
const form = ref({
name: '',
email: ''
})
const errors = ref({})
const submitForm = async () => {
try {
const { data, error } = await useFetch('/api/submit-form', {
method: 'POST',
body: form.value
})
if (error.value) {
if (error.value.response && error.value.response.status === 422) {
errors.value = error.value.response.data.errors
} else {
console.error('An unexpected error occurred:', error.value)
}
} else {
console.log('Form submitted successfully:', data.value)
}
} catch (err) {
console.error('An error occurred:', err)
}
}
</script>
In this example:
-
Template: The form template includes input fields for
nameandemail, and displays validation errors if they exist. -
Script Setup:
-
formis a reactive object holding the form data. -
errorsis a reactive object to store validation errors. -
submitFormis an async function that sends the form data to the backend usinguseFetch. - If the backend returns a 422 status code, the validation errors are extracted and stored in the
errorsobject.
-
This approach ensures that you can catch and display validation errors sent from your Laravel backend in your Nuxt 3 frontend.