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
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 routesweb.php
$path = storage_path($filename);
return response()->file($path);
});
And it can be accessed from browser like this,
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,
// 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 storagetest2.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.
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 storageapppublic folder. After creating a symlink, You can access this file storageapppublictest.webp from browser in this route,