Get "PHP 8 in a Nuthshell" (Soon includes PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Temporary and Signed URLs for Local Filesystem in Laravel

If you’re a long-time Laravel user, you might know about the feature that allows you to create temporary and signed URLs for files. This is a great feature that will enable you to share files with other users for a specified time.

The problem with this feature was it only works with the AWS S3 storage driver. So, if you’re working on your app in a local environment and you still want to test this feature, you must use the S3 storage driver and a real S3 bucket, which is sort of inconvenient since you need to have an AWS account to use this feature beforehand.

The updated local filesystem support

To get around this, the support for the temporary and signed URLs for files in the local filesystem has been added in Laravel 11.x (11.23.0).

So, once you update Laravel to this version, you need to make a few changes to your code to make temporary and signed URLs work for the local filesystem.

Updating the config/filesystems.php file

First, you need to set the server option to true for the local disk in the config/filesystems.php file like so.

'disks' => [
    //...
    'local' => [
        'driver' => 'local',
        'root' => storage_path('app/private'),
        'throw' => false,
        'serve' => true
    ],
]

This tells Laravel that the local filesystem is ready to serve signed URLs.

A new private folder

Next, you need to create a folder called private under the storage/app path and add the files you want to be served with signed URLs in it.

And that’s about it. Now, you can use the methods like Storage::temporaryUrl() to create temporary and signed URLs for the files in the private folder.

// File stored at: storage/app/private/laravel.png

$url = Storage::temporaryUrl(
    'laravel.png',
    now()->addSeconds(5)    
);

This will create a temporary URL for the file laravel.png that will be valid for 5 seconds.

In closing

I think this is a great improvement to the temporary and signed URLs feature in Laravel since it allows you to test this feature in a local environment without having to use a real S3 bucket.

Apart from this, you can even use this in production environment if you’re app is getting fairly moderate traffic. That way, you can skip relying on AWS S3 if it’s not necessary.

Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?