One of the most common things is to upload files such as images, pdf, etc. but usually, people forget the importance of protecting URLs when downloading our files.
Let's take an example, if we need to download something important like a contract and your URL is visible and accessible from anywhere, you would be exposing sensitive information to anyone who may have access to it.
Let's begin
For this example, I'll be using a small table of products like this
Now, we can define the fields in the Product model
class Product extends Model
{
protected $fillable = [
'name',
'uuid',
'price',
'image'
];
}
The next step is to create the route to download the files, open routes/web.php file and add
Route::get('products/{uuid}/download', 'ProductController@download')->name('products.download');
In the ProductController, we need to define the download function
public function download($uuid)
{
$product = Product::where('uuid', $uuid)->firstOrFail();
$pathToFile = storage_path('app/public/products/' . $product->image);
return response()->download($pathToFile);
}
Note: We need to generate a UUID when we store a new product, to generate a UUID you can use this article Generate UUID
Alright, now we need to go to our blade file and the route like this
<a href="{{ route('products.download', $product->uuid) }}">{{ $product->image }}</a>
This way we can protect our files.
Thanks for reading.