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
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.
}
}
The validation fails because Laravel only allows files that have actually been uploaded:
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.
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()usesis_uploaded_file()to check this.You could mark the file as a test to work around this "limitation":
But since
is_uploaded_file()is a security feature, you should be careful.