Performance: Retrieving files
This affects page load speed and user experience by how quickly files like images or documents are served from the server to the browser.
<?php // Using Laravel's built-in file streaming response $filePath = storage_path('app/public/file.pdf'); return response()->file($filePath);
<?php // Directly reading file contents and returning response $filePath = storage_path('app/public/file.pdf'); $content = file_get_contents($filePath); return response($content, 200)->header('Content-Type', 'application/pdf');
| Pattern | Memory Usage | Response Time | Network Load | Verdict |
|---|---|---|---|---|
| Reading full file into memory | High | Slow start, blocks rendering | High | [X] Bad |
| Streaming file with response()->file() | Low | Fast start, non-blocking | Moderate | [OK] Good |
| No cache headers | Low | Fast start | High on repeat loads | [!] OK |
| Streaming with cache headers | Low | Fast start | Low on repeat loads | [OK] Good |
Storage facade to interact with files in storage disks.Storage facade has methods like get() to retrieve file contents safely.example.txt stored in the default disk using Laravel's Storage facade?get() on the Storage facade.read(), fetch(), or open() do not exist on Storage facade.docs/manual.pdf exists in the default storage disk?if (Storage::exists('docs/manual.pdf')) {
echo Storage::path('docs/manual.pdf');
} else {
echo 'File not found';
}docs/manual.pdf exists in the storage disk.Storage::path() returns the full system path to the file, not a URL.$content = Storage::get('images/photo.jpg');
if ($content) {
echo 'File loaded';
} else {
echo 'No file';
}Storage::get() throws an exception instead of returning false or null.Storage::exists('images/photo.jpg') before calling get() to avoid errors.reports/summary.pdf stored on the public disk in Laravel. Which code snippet correctly achieves this?public disk, so we must specify it using Storage::disk('public').url() returns the public URL of the file on the specified disk.getUrl(). Storage::path('public/reports/summary.pdf'); returns a system path, not a URL.Pass the test and this pattern moves unknown