Laravel 6 Link Storage Folder Example

This tutorial explains, how you can link the storage folder and access file from there in laravel 6.

Note: The best approach is to create a symbolic link. To help with this, from version 5.3, Laravel includes a command that makes it incredibly easy to do.

You can use the below command for link storage folder in laravel:

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://yourdomain.com/storage/image.jpg

If, for any reason, you cannot create symbolic links (maybe you are on shared hosting, etc.) or you want to keep certain files safe behind some access control logic, there is an option to have a special route One who reads and provides 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;
});
Route::post('process', function (Request $request) {
    // cache the file
    $file = $request->file('photo');

    // generate a new filename. getClientOriginalExtension() for the file extension
    $filename = 'profile-photo-' . time() . '.' . $file->getClientOriginalExtension();

    // save to storage/app/photos as the new $filename
    $path = $file->storeAs('photos', $filename);

    dd($path);
});

Now you can access your files the same way you do a symlink:

http://somedomain.com/storage/image.jpg

If you are using the Intervention Image Library, you can make things more successful by using its built-in response method:

Route::get('storage/{filename}', function ($filename)
{
    return Image::make(storage_path('public/' . $filename))->response();
}); 

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *