how to return an error from laravel controller and catch it in Inertiajs using the form helper?

25 views Asked by At

I am trying to return an error in controller and because its not a laravel validation error i can't access it using the inertiajs form helper. i am trying avoid using the props.errors.

How to return the error in a way to access it using the inertiajs form helper?

controller:

return back()->withErrors(['name' => 'The name is invalid']);

vue:

<template>
  <div>
    <span v-if="form.errors.name" class="mt-1 text-sm text-red-700">
        {{ form.errors.name }}
    </span>
  </div>
</template>

<script setup>
    const form = useForm({
        name: null,
    })
</script>
1

There are 1 answers

0
Thomas Heck On

What are you trying to validate? I would recommend to let Laravel or HTML do the validation checking anyway, because they can validate almost anything.

However, you can set a custom error through javascript on the front-end for the form helper like this:

<template>
 <div>
  <span v-if="form.errors.name" class="mt-1 text-sm text-red-700">
    {{ form.errors.name }}
  </span>
 </div>
</template>

<script setup>
 const form = useForm({
     name: null,
 })

const submitForm = () => {
 if(/*your logic for invoking the error*/){
  form.setError('name', 'The name is invalid');
 }
}
</script>

If you want to return a custom error from your controller, you can do the same thing, but turn the field and error message into a prop. You could return your error like this:

//controller
return back()->with([
'customError' => [
 'field' => 'name',
 'message' => 'The name is invalid',
]
]);

Then on your front-end:

<template>
 <div>
  <span v-if="form.errors.name" class="mt-1 text-sm text-red-700">
    {{ form.errors.name }}
  </span>
 </div>
</template>

<script setup>
 import { computed } from 'vue';
 import { usePage} from '@inertiajs/vue3';
 const page = usePage();
 const customError = computed(() => page.props.customError);
 const form = useForm({
     name: null,
 })

 const submitForm = () => {
  if(/*your logic for invoking the error*/){
    form.setError(
     customError.value.field,
     customError.value.message
     );
  }
 }
</script>

If you want to turn your customError into a prop available to all inertia requests read about 'Flash messages' here: https://inertiajs.com/shared-data

More about form helper here: https://inertiajs.com/forms