Sunday, March 1, 2020

Laravel - How to access image uploaded in storage within View?

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();
});
https://stackoverflow.com/questions/30191330/laravel-5-how-to-access-image-uploaded-in-storage-within-view






Laravel 5 – Remove Public from URL

  1. Rename server.php in your Laravel root folder to index.php
  2. Copy the .htaccess file from /public directory to your Laravel root folder.

I have solved the issue using 2 answers:
  1. Renaming the server.php to index.php (no modifications)
  2. Copy the .htaccess from public folder to root folder (like rimon.ekjon said below)
  3. Changing .htaccess it a bit as follows for statics:
    RewriteEngine On
    
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [L,R=301]
    
    RewriteCond %{REQUEST_URI} !(\.css|\.js|\.png|\.jpg|\.gif|robots\.txt)$ [NC]
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
    
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_URI} !^/public/
    RewriteRule ^(css|js|images)/(.*)$ public/$1/$2 [L,NC]