Photo by Andy Mai on Unsplash

Stream file from AWS S3 or other external provider to user — Laravel

Marco Rivadeneyra
Sep 10 · 1 min read

When using an external storage provider like Aws S3, DigitalOcean Spaces or the likes, it’s not always a good idea to have our files directly served by them, there are some cases where we need to make sure our user is authenticated and can access the files before serving them the file.

One approach to this is processing the request using Laravel, and then streaming back the file to the user.

Route::get('/', function () {
$user = request()->user();
return response()->stream(function () use ($user) {
readfile("https://s3.amazonaws.com/MYBUCKET/{$user->uuid}.pdf");
},200, ['Content-Type' => 'application/pdf']);
});

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade