I have got user\'s avatars uploaded in Laravel storage. How can I access them and render them in a view?
The server is pointing all requests to /public
,
The best approach is to create a symbolic link like @SlateEntropy very well pointed out in the answer below. To help with this, since version 5.3, Laravel includes a command which makes this incredibly easy to do:
php artisan storage:link
That creates a symlink from public/storage
to storage/app/public
for you and that's all there is to it. Now any file in /storage/app/public
can be accessed via a link like:
http://somedomain.com/storage/image.jpg
If, for any reason, your can't create symbolic links (maybe you're on shared hosting, etc.) or you want to protect some files behind some access control logic, there is the alternative of having a special route that reads and serves the image. For example a simple closure route like this:
Route::get('storage/{filename}', function ($filename)
{
$path = storage_path('public/' . $filename);
if (!File::exists($path)) {
abort(404);
}
$file = File::get($path);
$type = File::mimeType($path);
$response = Response::make($file, 200);
$response->header("Content-Type", $type);
return $response;
});
You can now access your files just as you would if you had a symlink:
http://somedomain.com/storage/image.jpg
If you're using the Intervention Image Library you can use its built in response
method to make things more succinct:
Route::get('storage/{filename}', function ($filename)
{
return Image::make(storage_path('public/' . $filename))->response();
});
WARNING
Keep in mind that by manually serving the files you're incurring a performance penalty, because you're going through the entire Laravel request lifecycle in order to read and send the file contents, which is considerably slower than having the HTTP server handle it.