Laravel Symbolic Link

Securing and Accessing Laravel Symbolic Link Storage

In any real-world application; we often need to store uploaded files of the users. By default, Laravel stores the file inside the storage/app/public folder. But since it is not inside the public/storage folder; it cannot be accessed by the public. We need to create a symbolic link from public/storage to storage/app/public.

Option 1: Using Symbolic Link

To create the symbolic link, use the storage:link Artisan command:

php artisan storage:link

Once a file (say xyz.jpg) has been stored and the symbolic link has been created, simply create a URL to the files using the asset helper:

echo asset('storage/xyz.jpg');

More information on Symbolic Link is Available Here

Option 2: Using Routes

Although, a great way to store and access files; symbolic link also exposes all the files together to the public. In order to safeguard the files behind some logic simply use this code inside web.php

Route::get('/mystorage/{filename}', function ($filename)
{
    //Add additional Logic Here

    $path = storage_path('app/public/'.$filename); //translates to storage/app/public/filename

    if (!File::exists($path)) {
        abort(404); //return 404 error if file not found
    }

    $file = File::get($path); //get the file
    $type=File::extension($path); //determine the file type

    $response = Response::make($file, 200); //200 OK HTML Response
    $response->header("Content-Type", $type); //HTML filetype header

    return $response; //return file
});

You can access the file from blade like this

<!--In Blade-->
.
.
.
<a href="/mystorage/xyz.jpg">Click!</a>

I hope the code helps you.

close

Oh hi there 👋
It’s nice to meet you.

Sign up to receive awesome content in your inbox

We don’t spam! Read our privacy policy for more info.

Leave a Reply

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