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

Time:09-17

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/'.$request->product_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?

CodePudding user response:

$file->move($path, $fileName);

You are moving the file , check its moved there or not first.

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

Your errors seems to related with file that you moved is moved properly in that directory or not. it should solve if naming is correct

\File::copy(base_path('test.text'),base_path('public/test.text'));

Check name and move file.

CodePudding user response:

You may need a directory separator between your paths and the file name like this:

\File::copy($path.$fileName, $target.$fileName); // errors here
\File::copy($path.'/'.$fileName, $target.'/'.$fileName); // errors corrected

CodePudding user response:

You have to debug your code. Follow these steps either

  1. Try to print the value of file path. If you found anything wrong, change it.
  2. Open session.php file in config folder and look for storage_path
  3. Change your folder permission, but it saying no directory so may be issue is something else.
  4. Clear you config or other cache by using php artisan cache:clear or php artisan config:clear
  • Related