Courses

Vue.js 3 + Laravel 11 + Vite: SPA CRUD

Validation Errors: Catch and Show Them

Now, when we submit an empty form, the back-end API returns the 422 status code with errors, but there are no visible error messages for the user. Let's fix this.

validation errors


First, in the posts composable, we need to add a new object variable where all the errors will be saved, let's call it validationErrors and fill it inside the .catch function if there are any errors.

resources/js/composables/posts.js:

import { ref } from 'vue'
import { useRouter } from 'vue-router'
 
export default function usePosts() {
const posts = ref({})
const router = useRouter()
const validationErrors = ref({})
// ...
const storePost = async (post) => {
axios.post('/api/posts', post)
.then(response => {
router.push({ name: 'posts.index' })
})
.catch(error => {
if (error.response?.data) {
validationErrors.value = error.response.data.errors
}
})
}
 
return { posts, getPosts, storePost }
return { posts, getPosts, storePost, validationErrors }
}

Next, in the PostsCreate Vue component, we need to...

The full lesson is only for Premium Members.
Want to access all 27 lessons of this course? (115 min read)

You also get:

  • 69 courses (majority in latest Laravel 11)
  • Premium tutorials
  • Access to repositories
  • Private Discord