Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

487
Views
Laravel serve file from any path on server as if it was in the public folder

I want to be able to serve a file, located at any path on the server's filesystem that PHP/Apache has permission to read, as if it was in Laravel's public folder.

Let's say I have a local directory on my server /var/directory/ that contains two files:

  • /var/directory/abc.jpg
  • /var/directory/xyz.jpg

Now, how can I make these files accessible via something like:

  • https://example.com/media/abc.jpg
  • https://example.com/media/xyz.jpg

I think I need a controller that handles routes for /media/{filename}. It's fairly straight forward to then check if said file exists on disk in /var/directory/ and read it into PHP.

So the real question is: how I read these files efficiently and then serve them as a response to a get request? The solution should be as efficient as possible so that it works for larger files (10s to 100s of MB).

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

I figured it out by myself. I must say, the solution is embarassingly simple.

I have all files indexed in the DB, so I can make use of route model binding. If that isn't the case for you, you'd need to look up if the file exists on disk manually.

Route::get('/media/{file:id}', FileDownloadController::class);

Then, all it takes is:

public function __invoke(File $file)
{
    return response()->file($file->path);
}

Or this if a download prompt should be raised:

public function __invoke(File $file)
{
    return response()->download($file->path);
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!