Laravel function to convert a realpath() to an absolute URL

- 1 answer

Ad

I have declared a path pointing to a folder like this:

$path = realpath(public_path('uploads'));

This gives me that value: /var/www/mywebsite/public/uploads

Now, I want to turn this into an absolute URL, like this: http://www.mywebsite.com/uploads

Here is what I did:

dd(asset($path));     // Wrong: http://www.mywebsite.com/var/www/mywebsite/public/uploads
dd(url($path);        // Same.
dd(asset('uploads')); // Right, but I only want to use $path

Is there a pre-built way to achieve this in Laravel 5?

Ad

Answer

Ad

Yours $path is taken relatively to public folder with public_path('uploads'), so, 'uploads' by itself points to absolute path. Just add host part to it. Like:

$inPublic = 'uploads';
$localPath = realpath(public_path($inPublic));

// then, either
$url = url("/" . trim($inPublic, "/\\"));    

// or
$publicPath = realpath(public_path());
$relativePart = str_replace($publicPath, '', $localPath);
$url = url("/" . trim($relativePart, "/\\"));
Ad
source: stackoverflow.com
Ad