Nuxt - Laravel Precognition
GitHubNuxt Module
  • Getting Started
    • Introduction
    • Installation
  • Usage
    • Configuration
  • Validation
  • Error handling
  • File uploads
  • Use with Nuxt UI
  • Composables
    • usePrecognitionForm
    • usePrecognitionConfig
    • useNuxtFormValidator
  • Other
    • Breeze Nuxt template
    • Troubleshooting
Powered by GitBook
On this page

File uploads

Validate you files via Laravel Precognition with ease!

PreviousError handlingNextUse with Nuxt UI

Last updated 2 months ago

By default, Laravel Precognition does not upload or validate files during a precognitive validation request. This ensures that large files are not unnecessarily uploaded multiple times.

Because of this behavior, you should ensure that your application to specify the field is only required for full form submissions:

/**
 * Get the validation rules that apply to the request.
 *
 * @return array
 */
protected function rules()
{
    return [
        'avatar' => [
            ...$this->isPrecognitive() ? [] : ['required'],
            'image',
            'mimes:jpg,png',
            'dimensions:ratio=3/2',
        ],
        // ...
    ];
}

If you would like to include files in every validation request, you may set the validateFiles config in your nuxt.config.ts:

export default defineNuxtConfig({
  // ... other config

  precognition: {
    validateFiles: true,
  },
})

It is also possible to set this option directly on validate method call:

const validate = () => form.validate([], {
  validateFiles: true,
  onSuccess: (response) => {
    console.log('Success', response)
  },
  onError: (error) => {
    console.error('Error', error)
  },
  onValidationError: (response) => {
    console.warn('Validation error', response)
  },
})

In this case, we validate the whole form data, including files. Here is another example of the input with a validation callback on the change event:

<input
  id="avatar"
  type="file"
  @change="(event: Event) => {
    const input = event.target as HTMLInputElement
    form.fields.avatar = input.files?.item(0) ?? null
    form.validate('avatar', { validateFiles: true })
  }"
>

Keep in mind that if you have files attached to the API request, then Content-Type will be passed as multipart/form-data .

customizes the corresponding form request's validation rules