Skip to content

useSanctumForm()

The useSanctumForm() composable offers an easy way to handle form submissions with Laravel Sanctum authentication in Nuxt 3 applications. It is inspired by Laravel Precognition but specifically designed for Nuxt 3, which uses ofetch instead of axios. This composable leverages the useSanctumFetch() utility to provide a pre-configured ofetch client, allowing you to handle authentication securely and efficiently while simplifying form management and error handling in your app.

Example Usage

Here's how you can create a form for adding new users in your application:

vue
<script setup>
const form = useSanctumForm('post', 'api/users', {
    name: '',
    email: '',
});

const submit = () => form.submit();
const reset = () => form.reset();
</script>

<template>
    <form @submit.prevent="submit">
        <div>
            <label for="name">Name</label>
            <input
                id="name"
                v-model="form.name"
                @input="form.forgetError('name')"
            />
            <div v-if="form.invalid('name')">
                {{ form.errors.name }}
            </div>
        </div>

        <div>
            <label for="email">Email</label>
            <input
                id="email"
                type="email"
                v-model="form.email"
                @input="form.forgetError('email')"
            />
            <div v-if="form.invalid('email')">
                {{ form.errors.email }}
            </div>
        </div>

        <button type="submit" :disabled="form.processing">
            Create User
        </button>

        <button type="button" @click.prevent="reset">
            Reset
        </button>
    </form>
</template>

Handling Validation Errors

Any validation errors from the server automatically populate the errors object:

vue
<div v-if="form.invalid('email')">
    {{ form.errors.email }}
</div>

You can check if there are any form errors using the hasErrors property:

vue
<div v-if="form.hasErrors">
    <!-- Display error messages -->
</div>

Forgetting Errors

Manually clear form errors using the forgetError function:

vue
<input
    id="avatar"
    type="file"
    @change="(e) => {
        form.avatar = e.target.files[0];
        form.forgetError('avatar');
    }"
/>

Handling Form Submissions

You can execute additional logic upon a successful or failed submission using the submit function:

vue
const submit = () => form.submit()
    .then(response => {
        form.reset();
        alert('User created.');
    })
    .catch(error => {
        alert('An error occurred.');
    });

Processing State

Check if a form submission is in progress by inspecting the processing property:

vue
<button :disabled="form.processing">
    Submit
</button>

Setting Form Data

To pre-fill or set form data programmatically, use the setData function:

vue
form.setData({
  name: "John Doe",
  email: "john@example.com"
});