unknownUser17's avatar

Laravel File Copy: failed to open stream: No such file or directory

I am using File::copy to copy the uploaded file from the main folder into my target folder. But it keeps saying there is no such file or directory.

public function store(Request $request)
{        
    $data = $request->validate([
        'name' => 'required',
        'product_id' => 'required',
        'price' => 'required',
        'file' => 'required',
        'file.*' => 'mimes:jpeg,jpg,png,svg,gif,csv,xlsx,pdf,docx',
        'publish' => 'required',
    ]);

    $fileData = [];
    
    if($request->hasFile('file'))
    {
        foreach($request->file('file') as $file)
        {
            $path = public_path('storage/documents/'.$id);
            $fileName = time().'_'.$file->getClientOriginalName();
            $file->move($path, $fileName);

            $target = public_path('storage/documents/download');
            \File::copy($path.'/'.$fileName, $target.'/'.$fileName) // errors here

            $fileData[] = $fileName;
        }
        $data['file'] = json_encode($fileData);
    }

    $document = Document::create($data);

    return redirect()->route('product.index')->with('success','Document added successfully');
}

How can I solve this problem or is there any other way to upload same file on 2 folders?

0 likes
6 replies
Sinnbeck's avatar

What do you get if you dump the path? Can you find the file in that location?

$target = public_path('storage/documents/download');
dd($path.$fileName);
            \File::copy($path.$fileName, $target.$fileName); // errors here
unknownUser17's avatar

File is stored and moved to public path public/storage/documents/{id} and dd out "C:\wamp64\www\xxx\public\storage/documents/51631520676_Example.xlsx"`, I am not sure why the public_path() goes to backslash instead of forward slash..

siangboon's avatar

are you missing a "/" on your path and target?

siangboon's avatar

perhaps try reverse debug it by hardcoding a valid path and filename (exists) on the error step first and replace parameter by parameter until you find which part causing the error...

1 like
unknownUser17's avatar
unknownUser17
OP
Best Answer
Level 1

Thanks, @siangboon . I found the solution, the target directory needs to be created first to store the copied files from the main directory.

if (!File::exists(public_path('storage/documents/download'))) {
        File::makeDirectory(public_path('storage/documents/download'), 0775, true);
}
1 like

Please or to participate in this conversation.