Search code examples
laravellaravel-5intervention

Saving Intervention Image In Owners Folder in Laravel 5


I can change my code to save the uploaded image in the public dir but not when I want to their uploaded image in a folder as their company's name. For example of what works:

/public/company_img/<filename>.jpg

If the user's company name is Foo, I want this when they save save their uploaded image:

/public/company_img/foo/<filename>.jpg

This is in my controller:

$image = Input::file('company_logo');
$filename = $image->getClientOriginalName();
$path = public_path('company_img/' . Auth::user()->company_name . '/' . $filename);

// I am saying to create the dir if it's not there.
File::exists($path) or File::makeDirectory($path); // this seems to be the issue

// saving the file
Image::make($image->getRealPath())->resize('280', '200')->save($path);

Just looking at that you can easily see what it's doing. My logs shows nothing and the browser goes blank after I hit the update button. Any ideas


Solution

  • File::exists($path) or File::makeDirectory($path);
    

    This line does not make sense, as you check if a file exists and if not you want to attempt to create a folder ( in your $path variable you saved a path to a file not to a directory )

    I would do something like that:

            // directory name relative to public_path()
        $dir = public_path("company_img/username"); // set your own directory name there
    
        $filename = "test.jpg"; // get your own filename here
    
        $path = $dir."/".$filename;
    
        // check if $folder is a directory
        if( ! \File::isDirectory($dir) ) {
    
            // Params:
            // $dir = name of new directory
            //
            // 493 = $mode of mkdir() function that is used file File::makeDirectory (493 is used by default in \File::makeDirectory
            //
            // true -> this says, that folders are created recursively here! Example:
            // you want to create a directory in company_img/username and the folder company_img does not
            // exist. This function will fail without setting the 3rd param to true
            // http://php.net/mkdir  is used by this function
    
            \File::makeDirectory($dir, 493, true);
        }
    
    
        // now save your image to your $path
    

    But i really can't say your behaviour has something to do with that... Without error messages, we can only guess.