sidnas
sidnas

Reputation: 585

Laravel Form Request Validation rule "required" not working with null values

I have Laravel/Vue application and I'm submiting form with file and some other data using axios.

  this.loading = true;
  this.errors = {};

  let formData = new FormData();

  formData.append('type', this.type);
  formData.append('file', this.file);
  formData.append('date', this.date);

  axios.post(`/file-upload`,
      formData,
      {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
      .then((response) => {
        if (response.status === 200) {
          this.loading = false;
          // Success..
        }
      })
      .catch((error) => {
        this.loading = false;
        if (error.response.status === 422) { // Laravel XHR Requests errors
          this.errors = error.response.data.errors;
        } else {
          console.log(error);
        }
      });

In Laravel controller I have store method with form request validator

public function store(ImportRequest $request)
{
   // Request is valid..
}

ImportRequest

public function rules()
{
    return [
        'type' => 'required',
        'file' => 'required|mimes:xls,xlsx|file|max:512',
        'date' => 'required|date',
    ];
}

In my vue component default field values is null. And when I submitting empty form I'm expecting that validation will fail and return messages that fields are required but only errors I get is about file mimes, size and date. Nothing about required...

Request Headers Form Data

From Laravel documentation I understand that required rule must return error. "A field is considered "empty" if one of the following conditions are true: The value is null..." https://laravel.com/docs/8.x/validation#rule-required

For now only solution I think of is in javascript check values against null and only if not null add to FormData. In that case required rule works as I expect

Any ideas? Em I doing something wrong?

UPDATED | SOLVED

null is considered as string "null"

dd() request result

Upvotes: 2

Views: 2218

Answers (1)

N69S
N69S

Reputation: 17216

null is considered as a text 'null' wich validate the required condition (there is no Null in http form values.

What laravel consider Null is an empty value in postman. To be more precise, there is a middleware that switches empty value into Null values. You can disable it in kernel.php if you need the empty value to stay empty.

Upvotes: 1

Related Questions