Laravel |更改 file() 的 realPath 值

Laravel | Change realPath value of file()

是否可以更改 Laravel 文件的 realPath 属性?我实际上可以移动文件,但不能更改数据库记录,因为它被记录为旧的 realPath 而不是新路径。

这是我转储 $request->file('xx');

时得到的结果
UploadedFile {#476 ▼
  -test: false
  -originalName: "Screen Shot 2018-05-07 at 6.08.05 PM.png"
  -mimeType: "image/png"
  -size: 312932
  -error: 0
  #hashName: null
  path: "/Applications/MAMP/tmp/php"
  filename: "phpg4VH0Z"
  basename: "phpg4VH0Z"
  pathname: "/Applications/MAMP/tmp/php/phpg4VH0Z"
  extension: ""
  realPath: "/Applications/MAMP/tmp/php/phpg4VH0Z"
  aTime: 2018-05-09 13:33:43
  mTime: 2018-05-09 13:33:42
  cTime: 2018-05-09 13:33:42
  inode: 2003589
  size: 312932
  perms: 0100600
  owner: 501
  group: 80
  type: "file"
  writable: true
  readable: true
  executable: false
  file: true
  dir: false
  link: false
}

这是我的代码:

public function store(UploadRequest $request)
{
    $path = public_path('/uploads');

    $project = new Project($request->all());
    $project->save();

    foreach ($request->file() as $file) {
        dd($file);
        $fileName = time().'.'.$file->getClientOriginalExtension();
        $file->storeAs($path, $fileName);
    }

    return $request->all();
}

我想使用自定义名称将文件保存在 public/uploads 文件夹中,并在数据库中使用相同的 path/name。因为现在保存为/Applications/MAMP/tmp/php/phpGQhReP

你可以这样移动文件

$file->move(public_path('uploads'), $file->originalName);

这应该可以解决问题,它假设您的 <input 文件名为 file:

public function store(UploadRequest $request)
{
    if ($request->hasFile('file')) { // depends on your FormRequest validation if `file` field is required or not
        $path = $request->file->storePublicly(public_path('/uploads'));
    }

    Project::create(array_merge($request->except('file'), ['file' => $path])); // do some array manipulation

    return $request->all();
}

这用于上传多个文件:

public function store(UploadRequest $request)
{
    foreach ($request->file() as $key => $file) {
        if ($request->hasFile($key)) {
            $path = $request->$key->storePublicly('/uploads');
        }
        $keys[]  = $key;
        $paths[] = $path;
    }
    $data = $request->except($keys);
    $data = array_merge($data, array_combine($keys, $paths));

    Project::create($data);

    return back()->with('success', 'Project has been created successfully.');
}