How to create a temporary access link to files in Laravel
Overview
If you ever wanted to disable the link to a certain resource file after some time, this shot will help you accomplish that quickly.
What is a temporary access file link?
A temporary access file link is a link to a particular resource file with an expiration time.
In this shot, we are going to be using the temporaryUrl() method to achieve this.
$url = Storage::temporaryUrl(
'file.jpg', now()->addMinutes(5)
);
Syntax
$url = Storage::temporaryUrl();
Parameter
This method accepts two parameters:
- The path to the resource file.
DateTimewhich specifies when the link should expire.
Example
use Illuminate\Support\Facades\Storage;
$url = Storage::temporaryUrl(
'file.jpg', now()->addMinutes(5)
);
// send link to user here
Code explanation
- In the example above, we call the
temporaryUrl()method on theStoragefacade and pass the path to the file asfile.jpg. - We add the time to the link expiration in the second parameter as 5 minutes from the time the link was created.