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.
With over 3 years of versatile experience in IT Specialist, Project Manager, CTO, and Coding Instructor roles, I bring a comprehensive skill set to my current position as a Senior IT Support Analyst at RBC Capital Markets. I am proficient in stakeholder management, envisioning, producing, and delivering well-tested software products, and optimizing business processes. My passion lies in two key areas: technical writing and cloud engineering.
My expertise in technical writing is evidenced by published works on esteemed platforms like Techflow360, FreeCodeCamp, and Elsevier. In the realm of cloud engineering, I am further bolstered by my Google Cloud Associate Cloud Engineer certification.
At She Thinks Code, I actively contribute to offering computer science education to women from Least Developed Countries, harnessing technology to empower individuals. I am eager to explore collaborations and initiatives that capitalize on my expertise in diverse technical environments, including leveraging my cloud engineering skills.
