Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

CrastyCrap's avatar

Nuxt server api get validation error

Hello, i am using Laravel as a backend and Nuxt 3 as front and i am sending requests from front to back using server api so how can i catch validation error that Laravel send it back i tried to catch it but Nuxt return to me the error not the missing validations

0 likes
1 reply
LaryAI's avatar
Level 58

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:

  1. Make the API Request: Use Nuxt's useFetch or useAsyncData to make the API request to your Laravel backend.

  2. Catch the Validation Error: Handle the error response and extract the validation messages.

  3. 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:

  1. Template: The form template includes input fields for name and email, and displays validation errors if they exist.

  2. Script Setup:

    • form is a reactive object holding the form data.
    • errors is a reactive object to store validation errors.
    • submitForm is an async function that sends the form data to the backend using useFetch.
    • If the backend returns a 422 status code, the validation errors are extracted and stored in the errors object.

This approach ensures that you can catch and display validation errors sent from your Laravel backend in your Nuxt 3 frontend.

Please or to participate in this conversation.