Mikegk's avatar

Storage path problem

Hi guys,

Im currently struggling with the following problem:

I want to add a file using a method. Therefore I'm passing the full qualified path of the uploaded file which directly points to it:

//That looks like so:
/Users/username/projects/one-laravel-project/storage/app/public/upload/file.jpg

Within my method, I do need the absolute directory (like above without the filename) and a web callable path that should look like:

/storage/upload/

I managed both with the following code:


public static function addMediaFromFile($file_path)
    {

        //Path
        $directory = dirname($file_path);
        $file_name = basename($file_path);
        $file_path_relative = addTrailingSlash(Storage::url(substr($directory,strlen(storage_path('app/public/')))));
        $file_path_absolute = addTrailingSlash($directory);

//...
}

The "addTrailingSlash" function makes sure that both paths will end with a slash.

Please tell me that there is a more efficient way to get the relative path ($file_path_relative).

Thank you for any suggestions.

0 likes
4 replies
jlrdw's avatar

Make a constant.

Also early in laravel, I put in in index, define DS.

defined('DS') || define('DS', DIRECTORY_SEPARATOR);

then something like:

define('ASSET', realpath(dirname(__FILE__)). DS . 'assets' . DS);

Use your folder. I don't even know what addTrailingSlash is, but I will look it up.

Mikegk's avatar

Thank you. There must be a better way.

P.S.:

addTrailingSlash is just a helper function I wrote, that ensures a path ends with a "/".

Please or to participate in this conversation.