Search code examples
phplaravelfile-uploadlaravel-5.3image-uploading

How can I create folder dynamically when moving image?


I use laravel 5.3

My code to move image like this :

private function savePhoto($photos, $id)
{
    foreach($photos as $key => $photo) {
        $temp = storage_path() . DIRECTORY_SEPARATOR . 'temp' . DIRECTORY_SEPARATOR . $photo['name'];
        $destinationPath = public_path() . DIRECTORY_SEPARATOR . 'img'. DIRECTORY_SEPARATOR .'products'.DIRECTORY_SEPARATOR.$id.DIRECTORY_SEPARATOR.$photo['name'];
        if( rename( $temp , $destinationPath )){
            echo 'moved!';
        } 
        else {
            echo 'failed';
        }
    }
}

When executed there exist error like this :

rename(C:\xampp\htdocs\myshop\storage\temp\NOTFCjMipXwFhBICo1tj6VXP5Qhv92Fg1kmawcUd.jpeg,C:\xampp\htdocs\myshop\public\img\products\77\NOTFCjMipXwFhBICo1tj6VXP5Qhv92Fg1kmawcUd.jpeg): The system cannot find the path specified. (code: 3)

I think the error occurred because the $id folder is dynamically generated. The $id folder depends on the parameter id. If parameter id = 77, it will be formed like this:

C:\xampp\htdocs\myshop\public\img\products\77\NOTFCjMipXwFhBICo1tj6VXP5Qhv92Fg1kmawcUd.jpeg

So the error occurred because folder 77 does not exist yet

How to make folder 77(This is dynamically generated) first before moving the image?

Update

Sample array results from $photos like this :

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => vYcHWLXpwhC9WfXd4XCB2emg83WMtWHphyUBq9MV.jpeg
        )

    [1] => Array
        (
            [id] => 2
            [name] => 1STr51oF8cunSsNEJZyS9upI0hNHYMXjLCCSNonz.jpeg
        )

)

Solution

  • Use mkdir()

    private function savePhoto($photos, $id)
    {
        foreach ($photos as $key => $photo) {
            $temp = storage_path() . DIRECTORY_SEPARATOR . 'temp' . DIRECTORY_SEPARATOR . $photo['name'];
    
            $idDir = public_path() . DIRECTORY_SEPARATOR . 'img' . DIRECTORY_SEPARATOR . 'products' . DIRECTORY_SEPARATOR . $id;
            $destinationPath = $idDir . DIRECTORY_SEPARATOR . $photo['name'];
    
            if (!is_dir($idDir)) {
                mkdir($idDir, 0777, TRUE);
            }
    
            if (rename($temp, $destinationPath)) {
                echo 'moved!';
            } else {
                echo 'failed';
            }
        }
    }