Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jbtje's avatar
Level 3

file upload, isValid() returns false

The UploadFile::fake()->create(...) method does create a file on the disk, however it is always empty no matter the kb size you enter. If you use this method for testing, it works fine and $this->file('name')->isValid() returns true. Even ->getSize() returns a value larger than 0, while the file received still is empty.

I however need to upload a "real" file, that is, one with content. Thus the following code:

$name = 'RandomFilename.abc';
Storage::put('TEST/' . $name, "Some Content");

$path = storage_path() . '/app/TEST/' . $name;
$hashes[] = hash_file( 'sha256', $path );
$files[] = UploadedFile::createFromBase( new \Symfony\Component\HttpFoundation\File\UploadedFile($path, $name) );

$this->json( 'POST', '/api/upload', ['hashes' => $hashes, 'files' => $files] );

My controller:

if( $files = $request->file( 'files' ) ) {
    foreach( $files as $i => $file ) {
        if( !$file->isValid() ) {
            throw new UploadFileInvalidException();
        }

        // ... more validation

        $file->storeAs( 'data', $hashes[ $i ] . '.j' );
    }
}

Same controller for UploadedFile and the real file method, however isValid() returns false when I upload a real file!?

dd($file) returns when using real file

Illuminate\Http\UploadedFile {#682
  -test: false
  -originalName: "675327166.j"
  -mimeType: "application/octet-stream"
  -size: null
  -error: 0
  #hashName: null
  path: "FULL PATH HERE\storage/app/TEST"
  filename: "675327166.j"
  basename: "675327166.j"
  pathname: "FULL PATH HERE\storage/app/TEST/675327166.j"
  extension: "j"
  realPath: "FULL PATH HERE\storage\app\TEST\675327166.j"
  aTime: 2017-10-19 22:00:00
  mTime: 2017-10-19 23:52:38
  cTime: 2017-10-19 23:52:36
  inode: 0
  size: 1020
  perms: 0100666
  owner: 0
  group: 0
  type: "file"
  writable: true
  readable: true
  executable: false
  file: true
  dir: false
  link: false
  linkTarget: "FULL PATH HERE\storage\app\TEST\675327166.j"
}

couple of things:

  • "-size" is null, which is weird, since "size" is 1020

  • For some reason PHP knows the full path to my file!? Correct me if I'm wrong, but I believe PHP can only know the original filename, not the path, when uploading using a form. Which makes me believe that the unitTest does not upload a file, but the object of the file? If I do dd($file) in the unitTest, I get the exact same result, which proofs my point.

  • So, how to truly upload a file using laravel 5.5 unitTest?

  • Why is isValid() false?

  • Why is the UploadedFile::fake() empty?

0 likes
0 replies

Please or to participate in this conversation.