moses's avatar
Level 2

How do I upload files on 2 folders at once in one method on the laravel?

I use laravel 5.6

I want to upload files on 2 folders at once. So if the image uploaded successfully in the product folder, I want the image uploaded in the thumbs folder as well

I try like this :

public function uploadImage($file)   
{
    if($file) {
        $fileName = str_random(40) . '.' . $file->guessClientExtension();
    }

    $destinationPath = storage_path() . DIRECTORY_SEPARATOR . 'app' . DIRECTORY_SEPARATOR . 'public' . DIRECTORY_SEPARATOR . 'product';

    if(!File::exists($destinationPath)) {
        File::makeDirectory($destinationPath, 0755, true);
    }

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

    $destinationPathThumb = storage_path() . DIRECTORY_SEPARATOR . 'app' . DIRECTORY_SEPARATOR . 'public' . DIRECTORY_SEPARATOR . 'product' . DIRECTORY_SEPARATOR . 'thumb';

    if(!File::exists($destinationPathThumb)) {
        File::makeDirectory($destinationPathThumb, 0755, true);
    }

    $image_resize = Image::make($file->getRealPath());  
    $image_resize->resize(300, 300);
    $image_resize->save($destinationPathThumb . DIRECTORY_SEPARATOR . $fileName);
    
    return $fileName;
}

If the code run, it just success to upload in the product folder. It did not upload in the thumbs folder

There exist error like this :

message Unable to find file (/tmp/phpUSxbEJ).

exception Intervention\Image\Exception\NotReadableException

I try run this code :

public function uploadImage($file) 
{
    if($file) {
        $fileName = str_random(40) . '.' . $file->guessClientExtension();
    }
    $destinationPathThumb = storage_path() . DIRECTORY_SEPARATOR . 'app' . DIRECTORY_SEPARATOR . 'public' . DIRECTORY_SEPARATOR . 'product' . DIRECTORY_SEPARATOR . 'thumb';

    if(!File::exists($destinationPathThumb)) {
        File::makeDirectory($destinationPathThumb, 0755, true);
    }
    $image_resize = Image::make($file->getRealPath());  
    $image_resize->resize(300, 300);
    $image_resize->save($destinationPathThumb . DIRECTORY_SEPARATOR . $fileName);
    return $fileName;
}

So I remove code to upload in product folder. I try it and it works. It success upload on the thumbs folder

So I think in one process, it only upload in one folder

Is there any other way to upload on 2 folders?

0 likes
2 replies
skliche's avatar
skliche
Best Answer
Level 42

$file->getRealPath() is not returning the path of the moved file.

$file->move() returns a new File instance. Try $file = $file->move($destinationPath, $fileName); instead.

Please or to participate in this conversation.