Usage

File uploads

Validate you files via Laravel Precognition with ease!

Usage

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 customizes the corresponding form request's validation rules to specify the field is only required for full form submissions:

app/Http/Requests/MyRequest.php
<?php

// other code ...

final class MyRequest extends FormRequest
{
    /**
     * 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:

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.