Framework: FormRequest prepareForValidation not working with files

Created on 1 Dec 2018  路  2Comments  路  Source: laravel/framework

  • Laravel Version: 5.6
  • PHP Version: 7.2.9
  • Database Driver & Version: Mysql MariaDB 10.2.14

Description:

I want to upload a file manually. Although it is UploadedFile object but I cannot pass the validation.

failedValidation Message: The file failed to upload.

I think it doesn't work prepareForValidation with files preparing.

reference: https://github.com/laravel/framework/issues/7995#issuecomment-82269811

Steps To Reproduce:

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\UploadedFile;

class StoreDocument extends FormRequest
{
    protected function prepareForValidation()
    {
        $uploadedFile = new UploadedFile($file_path, $file_original_name);

        $this->files->replace([
            'file' => $uploadedFile
        ]);

        $this->merge([
            'file' => $uploadedFile,
        ]);
    }

    ...

    public function rules()
    {
        # checked 
        dd($this->file('file')) // OK -> UploadedFile Object
        dd($this->input('file')) // OK -> UploadedFile Object

        return [
            'file' => 'required|file|size:10485'
        ];
    }

    protected function failedValidation(Validator $validator)
    {
        dd($validator->errors()); # The file failed to upload.
    }

}

Most helpful comment

The validation fails because Laravel only allows files that have actually been uploaded:

https://github.com/laravel/framework/blob/a64a900607f110bd365a0265dddd8278badfbed8/src/Illuminate/Validation/Validator.php#L379

isValid() uses is_uploaded_file() to check this.

You could mark the file as a test to work around this "limitation":

$uploadedFile = new UploadedFile($file_path, $file_original_name, null, null, true);

But since is_uploaded_file() is a security feature, you should be careful.

All 2 comments

The validation fails because Laravel only allows files that have actually been uploaded:

https://github.com/laravel/framework/blob/a64a900607f110bd365a0265dddd8278badfbed8/src/Illuminate/Validation/Validator.php#L379

isValid() uses is_uploaded_file() to check this.

You could mark the file as a test to work around this "limitation":

$uploadedFile = new UploadedFile($file_path, $file_original_name, null, null, true);

But since is_uploaded_file() is a security feature, you should be careful.

@staudenmeir thank you for information. Nice tricks!

I would like to write about why I need such a thing. Maybe people might wonder why I need something like that.

I have a documents table and i am saving more than 20 columns about document specifications in document controller when uploaded files. I wanted to choose this way because I didn't want to add these properties one by one when I generated pdf on the server. It's easy to put into the FormRequest object and save model.

Was this page helpful?
0 / 5 - 0 ratings