How to get file URL using Storage facade in laravel 5?
This method exists since Laravel 5.4, you can get it by:
$path = Storage::disk('public')->path($filename);
Edit: Solution for L5.2+
There's a better and more straightforward solution.
Use Storage::url($filename)
to get the full path/URL of a given file. Note that you need to set S3
as your storage filesystem in config/filesystems.php
: 'default' => 's3'
Of course, you can also do Storage::disk('s3')->url($filename)
in the same way.
As you can see in config/filesystems.php
there's also a parameter 'cloud' => 's3'
defined, that refers to the Cloud filesystem. In case you want to mantain the storage folder in the local server but retrieve/store some files in the cloud use Storage::cloud()
, which also has the same filesystem methods, i.e. Storage::cloud()->url($filename)
.
The Laravel documentation doesn't mention this method, but if you want to know more about it you can check its source code here.
This is how I got it to work - switching between s3 and local directory paths with an environment variable, passing the path to all views.
In .env:
APP_FILESYSTEM=local or s3
S3_BUCKET=BucketID
In config/filesystems.php:
'default' => env('APP_FILESYSTEM'),
In app/Providers/AppServiceProvider
:
public function boot()
{
view()->share('dynamic_storage', $this->storagePath());
}
protected function storagePath()
{
if (Storage::getDefaultDriver() == 's3') {
return Storage::getDriver()
->getAdapter()
->getClient()
->getObjectUrl(env('S3_BUCKET'), '');
}
return URL::to('/');
}
The Path to your Storage disk would be :
$storagePath = Storage::disk('local')->getDriver()->getAdapter()->getPathPrefix()
I don't know any shorter solutions to that...
You could share the $storagePath to your Views and then just call
$storagePath."/myImg.jpg";