Felix
Felix

Reputation: 121

Form Validation Responses with Inertia and Laravel 11

I'm having a form like:

<form @submit.prevent="submitForm">
    <div>
        <span v-if="form.errors.zipCode">{{ form.errors.zipCode }}</span>
        <Text label="Zip Code" name="zipCode" v-model="form.zipCode"></Text>
    </div>
    <Button type="submit" label="Send"></Button>
</form>

And a script like:

<script setup>
    import Text from '@/Components/Forms/Text.vue';
    import { useForm } from '@inertiajs/vue3';

    const props = defineProps({
        errors: {
            type: Object,
            required: false
        }
    });

    const components = {
        Text
    };

    const form = useForm({
        _token: document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
        zipCode: null,
    });

    const submitForm = () => {
        form.post('/post/create-account', {
            onSuccess: () => {
                console.log('success');
            },
            onError: (errors) => {
                console.log('Errors:', errors);
            }
        });
    }
</script>

And a Controller like this:

class RegistrationController extends FormController
{
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            '_token' => 'required|string',
            'zipCode' => 'required|string|max:5'
        ]);

        if ($validator->fails()) {

            // I've tried all this here
            // return redirect()->back()->withErrors($validator)->withInput();
            // throw ValidationException::withMessages($validator->errors()->toArray());
            // return back()->withErrors($validator)->withInput();
            // return redirect()->back()->withErrors($validator);
            // return back()->withErrors($validator->errors()->first());
            // return Inertia::render('Home', ['errors' => $validator->errors()->first()]);
            // return $validator->errors()->first();

            return '?';
        }

        // bla

        return '?';
    }
}

Now my question: What is the form.post expecting to trigger the onError? I don't manage to get it triggered. The console always tells me 'success' or the full page is loaded in this popup (where errors are also displayed, happens on Inertia::render()) and the url changes to "/post/create-account". Btw. I also tried to send status code 422 with plain json response but it doesn't work either. How does this work? I am grateful for any help, thank you ;))

Upvotes: 0

Views: 74

Answers (1)

Charlie Tennant
Charlie Tennant

Reputation: 81

All you need to do is change your validation routine to use the validate() method on the Request object rather than using the Validate::make() facade:

$request->validate([
    '_token' => 'required|string',
    'zipCode' => 'required|string|max:5'
]);

If a validation error occurs, this should be automatically handled, so you don't need to catch it in your method with if ($validator->fails()).

I've given this a test and it seems to work with your existing Vue markup.

Also by the way the CSRF token should already be automatically included with all Inertia and Axios requests.

Hope this helps!

Upvotes: 0

Related Questions