Search code examples
phplaravelfilelaravel-5upload

Laravel | Change realPath value of file()


Is it possible to change realPath attribute of Laravel file? I can actually move the file, but can't change the database record, as it's recorded as old realPath not the new path.

Here's what I get when I dump $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
}

And here's my code:

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();
}

I want to save the file inside public/uploads folder, with a custom name, and same path/name in database. As it's save as /Applications/MAMP/tmp/php/phpGQhReP for now.


Solution

  • This should do the trick, it assumes your <input with file is named 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();
    }
    

    And this for uploading multiple files:

    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.');
    }