Search code examples
laravellaravel-11

Storage::put creates file always with hash name instead of what is provided


I have a simple disk configuration like

'uploads' => [
  'driver' => 'local',
  'root' => storage_path('app/uploads'),
  'throw' => false,
],

When I call

$full_path = Storage::disk("uploads")->put("my_image.jpg", $file);

It outputs something like

"my_image.jpg/b5JsD4bs3BtBaja2YcI6o8wGdw8llxDvec4qsbgi.jpg"

I do understand that it is much safer to use the hashName of the file, but I'd like to have the control over how the file is named. I could not find anything in the docs about how to change this behaviour (didn't even find this behaviour documented).

I would not expect a folder named "my_image.jpg" to be created.


Solution

  • Looking at the API documentation for the put() method, the first argument is actually string $path, so where the file is saved, and not the name of the file. Using put('my_image.jpg, $file); and seeing the result of "my_image.jpg/b5JsD4bs3BtBaja2YcI6o8wGdw8llxDvec4qsbgi.jpg" would make sense based on that information.

    Thankfully, there's the putFileAs() method which should work for your needs:

    $fullPath = Storage::disk('uploads')->putFileAs('/', $file, 'my_image.jpg');
    // <full path to>/app/uploads/my_image.jpg