Probably you have heard about Laravel storage paths. They are a great way to manage files. Here is a simplified explanation about them.
you may have noticed there is two folders in Laravel root folder. One is public and other is storage. Let us see the difference first.
Let us store the same file inside both folders. We saved "test.webp" file inside both public and storage folders.
Now the image stored inside public folder can be accessed easily from browser like this
http://localhost:8000/test.webp
But we can't access the file stored in storage/test.webp
from browser like this. But we can access that file like this,
Inside routes\web.php
Route::get('storagepath/{filename}', function ($filename) {
$path = storage_path($filename);
return response()->file($path);
});
And it can be accessed from browser like this,
http://localhost:8000/storagepath/test.webp
Now the important think to understand is there is no actual path called storagepath in root. It is created in runtime. Advantage here is you can restrict access to files from this routes,
Route::get('storagepath/{filename}', function ($filename) {
// Construct the full path to the file
if ($filename == 'test.webp') {
$path = storage_path($filename);
// Check if the file exists
if (!file_exists($path)) {
// If the file does not exist, return a 404 Not Found error
abort(404);
}
return response()->file($path);
}
// Deny access to 'test2.webp' or any other file
abort(403, 'Unauthorized access.');
});
Now imagine we have a file stored inside storage\test2.webp
directory. The file will not be able to access from route like this
This way we can restrict logged in users from accessing other peoples images or files. Or can add any other restriction.
Public access for storage files.
There is a way to open some part of storage folder to public.
php artisan storage:link
This code will create a symlink from storage folder to public folder. Symlink is a short cut. Check here,
This has created a short cut from public to storage\app\public folder. After creating a symlink, You can access this file storage\app\public\test.webp from browser in this route,
http://localhost:8000/storage/test.webp
Top comments (0)