Accessing images in storage from public view

When we upload images in our project it gets saved into the storage folder. In some case, we want to access these images by calling them in views, in that case, we have to create a symbolic link. The versions above Laravel 5.3 has a command for it.

php artisan storage:link

This will create the link and now you can access any file by this link.

If you cannot create a symlink you should try the below code. It is a route which serves and reads the image.

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;

});