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