Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here

Validation Errors: Catch and Show Them

Premium
4 min read

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 of our courses? (29 h 14 min)

You also get:

54 courses
Premium tutorials
Access to repositories
Private Discord
Get Premium for $129/year or $29/month

Already a member? Login here

Comments & Discussion

G
guidutra ✓ Link copied!

Hi, I am getting this error and I could not find why. Could you please help? The

[Vue warn]: Property "validationErrors" was accessed during render but is not defined on instance. at <Create onVnodeUnmounted=fn<onVnodeUnmounted> ref=Ref< null > > at <RouterView> at <App>

G
guidutra ✓ Link copied!

I found the problem. It was on this line..

const { storePost, validationErrors } = usePosts()