Pida's avatar
Level 7

Get filename assigned by Storage put() method

I want to upload files, rename them and store both the original filename and the filename assigned by the Storage classes put() method in a database table.

This is from my view:

 <div class='form-group  {{ $errors->has("files") ? "has-error" :  "" }} '>
          <label for='files'>Files</label>
          <input type="file" name="files[]" multiple />
          {!! $errors->first('files', '<span class="Error">:message</span>') !!}
 </div>

And this is an excerpt from my controller:

    // Move files
    $files = $request->file('files');

    // If the array is not empty
    if ($files[0] != '') {
      // Set the destination path
      $destinationPath = 'public/uploads/' . $newId . '/';

      foreach ($files as $file) {

        // Store file. Filename is set automatically.
        Storage::disk('local')->put($destinationPath, $file);
  return $file->getFilename();
        $originalName = Str::lower($file->getClientOriginalName());
        FilenameMapping::create(['originalName' => $originalName,
                                 'storageName'  => ""]);
      }
    }

Right now I'm not creating a database entry, instead I return a filename. At this point, I'd like to get the filename set by the put() method - something like a741465eg86z264149cez41f3ee11648.png. Instead, I get the temporary filename from the directory the file was stored in after uploading, but before processing by my controller method - something like phpwHlpob.

What can I do to get the filename assigned by the put() method?

Thanks, Pida

0 likes
4 replies
Pida's avatar
Pida
OP
Best Answer
Level 7

I expected the put() method to return a boolean, but I was wrong: It returns the destination path.

So the solution is

// Store the file and it's destination path INCLUDING THE NEW FILENAME
$storagePath = Storage::disk('local')->put($destinationPath, $file);
// Extract the filename
$storageName = basename($storagePath);
9 likes
tepchiva's avatar

// Manually specify a file name... Storage::putFileAs('photos', new File('/path/to/photo'), 'photo.jpg');

Please or to participate in this conversation.